我有一个类,看起来像这样:
enum Name<'a> {
Single(&'a str),
Double(&'a str, &'a str),
}
还有另一种非常相似的类型,长这样:
enum OwnedName {
Single(String),
Double(String, String),
}
我已经有一种将Name转换为OwnedName的方法。但是,我无法想出一种实现类似于Deref
或Borrow
的方式来将OwnedName转换回Name。这意味着我必须写两次相同的方法,这很烦人。我希望有一些东西可以模仿PathBuf
/Path
或String
/str
的工作方式。我尝试了以下代码:
impl ops::Deref for OwnedName {
type Target = Name;
fn deref(&self) -> &Name {
match *self {
OwnedName::Single(ref s) => Name::Single(&**s),
OwnedName::Double(ref s1, ref s2) => Name::Double(&**s1, &**s2),
}
}
}
这个错误是关于 type Target = Name
的生命周期参数数量错误:期望 1 个,但找到了 0 个。这很容易理解,因为它需要一个生命周期。但我无法提供。那么有没有办法让我以这种方式使用 Deref
、Borrow
或 ToOwned
呢?
str
相同,比较和哈希方式是否一致?如果不是,则无法实现Borrow<str>
。 - blussstr
一样比较和哈希相同,因为我的一个变量中有两个字符串。 - Ben S