4

在以下场景中:

#[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需要返回一个引用。

4

0 回答 0