我想专攻&'static str
来自 &'a 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 会永远支持终生特化吗?
最佳答案
Rust 1.51.0 没有任何类型的专门化。如果我正在阅读 the specialization RFC正确,那么即使实现了 RFC,生命周期特化也将不被支持:
A hard constraint in the design of the trait system is that dispatch cannot depend on lifetime information. In particular, we both cannot, and should not allow specialization based on lifetimes:
We can't, because when the compiler goes to actually generate code ("trans"), lifetime information has been erased -- so we'd have no idea what specializations would soundly apply.
We shouldn't, because lifetime inference is subtle and would often lead to counterintuitive results. For example, you could easily fail to get
'static
even if it applies, because inference is choosing the smallest lifetime that matches the other constraints.
(强调我的)
链接中还有一些示例说明了一些具体问题。
我建议使用 Cow
来处理“拥有或借用”的情况。
关于rust - 是否可以专注于静态生命周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37053567/