问题描述
我正在尝试使用。我的程序中“键”的强类型包装器,这样我就不会将任意字符串误认为是键。我有:
#[derive(Debug,Clone,PartialEq,Eq,Hash)]
struct Key(String);
我有一个 HashMap<Key,_>
,我想通过对键类型的引用来查找值(即不必拥有字符串)。看来我需要做的是:
- 为我的密钥创建一个“ref”类型:
#[derive(Debug,Hash)]
struct KeyRef<'a>(&'a String);
(实际上我想要 KeyRef<'a>(&'a str)
,但使用 String
是一个更清晰的例子)
- 实现
Borrow<KeyRef<'_>> for Key
我已经尽力了,这是playground link
我最明确的尝试(注释所有生命周期)是:
impl<'a> Borrow<KeyRef<'a>> for Key {
fn borrow<'b>(&'b self) -> &'b KeyRef<'a> where 'b: 'a {
let string_ref : &'a String = &self.0;
let key_ref : &'a KeyRef<'a> = &KeyRef(string_ref);
key_ref
}
}
这给了我错误:“方法 borrow
上的生命周期参数或边界与特征声明不匹配”。
直觉上感觉这应该是可能的:
- KeyRef 持有生命周期为
'a
的引用,因此 KeyRef 的任何值都不能超过'a
。 - 在
fn borrow<'b>(&'b self)
中,由于上述原因,'b
不能大于'a
但编译器似乎不喜欢我的明确尝试来证明这一点(使用 where 'b: 'a
),如果不这样做,我会“由于需求冲突,无法推断借用表达式的适当生命周期”
解决方法
据我了解你的情况,你把事情不必要地复杂化了。一个简单的实现:
use std::collections::HashMap;
use std::borrow::Borrow;
#[derive(Debug,Clone,PartialEq,Eq,Hash)]
struct Key(String);
impl Borrow<str> for Key {
fn borrow(&self) -> &str {
&self.0
}
}
impl Borrow<String> for Key {
fn borrow(&self) -> &String {
&self.0
}
}
fn main() {
let mut map = HashMap::new();
map.insert(Key("one".to_owned()),1);
// Because Key is Borrow<String>
println!("{:?}",map.get("one".to_owned()));
// Because Key is Borrow<str>
println!("{:?}",map.get("one"));
}