我想从
要点是,
问题在于该代码无法编译:
&'a str
中专门使用 &'static str
: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!();
}
}
}
要点是,
MyString
将静态分配的字符串字面量存储为 &'static str
,而将所有其他字符串存储为 String
。这使得 MyString
避免了生命周期参数(即 MyString<'a>
),这对于我的 API 至关重要,同时允许调用者传入任何类型的字符串,并且让 MyString
自动执行正确的操作。问题在于该代码无法编译:
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`
有没有什么技巧可以让我做我想做的事情?如果没有,终身专业化是否是Rust将要支持的功能?