在以下场景中:
#[derive(PartialEq, Eq, Hash)]
struct Key(String);
fn get_from_map(map: HashMap<Key, i32>, key: &str) {
// ???
}
我可以通过使用Borrow
特征来实现这一点,所以我不需要 a &Key
,只需要 a 就&str
可以了:
impl Borrow<str> for Key {
fn borrow(&self) -> &str {
&self.0
}
}
fn get_from_map(map: HashMap<Key, i32>, key: &str) {
map.get(key);
}
但是,当我的密钥是枚举时,无法实现Borrow
:
#[derive(PartialEq, Eq, Hash)]
enum Key {
Text(String),
Binary(Vec<u8>)
}
fn get_from_map(map: HashMap<Key, i32>, key: &str) {
// ???
}
是否有一种符合人体工程学的方法来实现get_from_map
,无需克隆key
,以便它以某种方式只查找Text
键?
我的第一直觉是实现Borrow
一个BorrowedKey
新类型,但这似乎不起作用,因为Borrow
需要返回一个引用。