In the following scenario:
#[derive(PartialEq, Eq, Hash)]
struct Key(String);
fn get_from_map(map: HashMap<Key, i32>, key: &str) {
// ???
}
I can implement this by using the Borrow
trait, so I don't need a &Key
, just a &str
is fine:
impl Borrow<str> for Key {
fn borrow(&self) -> &str {
&self.0
}
}
fn get_from_map(map: HashMap<Key, i32>, key: &str) {
map.get(key);
}
However, when my key is an enum, there's no way to implement Borrow
:
#[derive(PartialEq, Eq, Hash)]
enum Key {
Text(String),
Binary(Vec<u8>)
}
fn get_from_map(map: HashMap<Key, i32>, key: &str) {
// ???
}
Is there an ergonomic way to implement get_from_map
, without cloning key
, so that it somehow only looks for Text
keys?
My first instinct is implement Borrow
for a BorrowedKey
newtype but that doesn't seem to work since Borrow
needs to return a reference.