我想专攻&'static str
from &'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 没有任何类型的专门化。如果我在读书专业化 RFC https://github.com/rust-lang/rfcs/blob/master/text/1210-impl-specialization.md#interaction-with-lifetimes正确的话,那么终身专业化将not即使实现了 RFC,也能得到支持:
特质系统设计中的一个硬约束是调度
不能依赖于生命周期信息。尤其,我们都不能,
并且不应允许基于生命周期的专业化:
(强调我的)
链接中还有一些示例表明了一些具体问题。
我建议使用Cow
处理“自有或借用”案件。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)