4

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.

rvidal
  • 2,012
  • 1
  • 17
  • 24
  • 1
    Something like [this](https://play.rust-lang.org/?gist=ef79aaf7926aa03b5127d26302efbe7a&version=stable&mode=debug)? – Peter Hall May 31 '18 at 23:13
  • 1
    You need the same implementation to work for both types of key? – Peter Hall May 31 '18 at 23:35
  • 1
    I believe your question is answered by the answers of [How to implement HashMap with two keys?](https://stackoverflow.com/q/45786717/155423). See also the answer to [How to avoid temporary allocations when using complex key for HashMap?](https://stackoverflow.com/a/50478038/155423) which is the same logic. If you disagree, please [edit] your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Jun 01 '18 at 00:28
  • 1
    The [duplicate applied to your situation](https://play.rust-lang.org/?gist=3eb216ccefb1533fea1a0e1dff5627f8&version=stable&mode=debug). – Shepmaster Jun 01 '18 at 01:38
  • @PeterHall Sorry I wasn't specific enough. My intent was not to clone the string. – rvidal Jun 01 '18 at 05:47

0 Answers0