É possível se especializar em uma vida estática?
Eu quero me especializar&'static str
de&'a str
. Algo assim:
use std::borrow::Cow;
struct MyString {
inner: Cow<'static, str>,
}
impl From<&'static str> for MyString {
fn from(x: &'static str) -> Self {
MyString {
inner: Cow::Borrowed(x),
}
}
}
impl<T: Into<String>> From<T> for MyString {
fn from(x: T) -> Self {
MyString {
inner: Cow::Owned(x.into()),
}
}
}
fn main() {
match MyString::from("foo").inner {
Cow::Borrowed(..) => (),
_ => {
panic!();
}
}
let s = String::from("bar");
match MyString::from(s.as_ref()).inner {
Cow::Owned(..) => (),
_ => {
panic!();
}
}
match MyString::from(String::from("qux")).inner {
Cow::Owned(..) => (),
_ => {
panic!();
}
}
}
A essência é queMyString
armazena uma literal de cadeia alocada estaticamente como um&'static str
e todas as outras cordas comoString
. Isso permiteMyString
para evitar um parâmetro vitalício, ou seja,MyString<'a>
, o que é essencial para a minha API, enquanto permite que o chamador passe qualquer tipo de string e tenhaMyString
faça automaticamente a coisa correta.
O problema é que o código não compila:
error[E0119]: conflicting implementations of trait `std::convert::From<&'static str>` for type `MyString`:
--> src/main.rs:15:1
|
7 | impl From<&'static str> for MyString {
| ------------------------------------ first implementation here
...
15 | impl<T: Into<String>> From<T> for MyString {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `MyString`
Existe algum truque que me permita fazer o que quero? Se não, a especialização vitalícia é algo que a Rust apoiará?