Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HashMap.entry() should allow for lookups by reference #51604

Closed
mqudsi opened this issue Jun 16, 2018 · 2 comments
Closed

HashMap.entry() should allow for lookups by reference #51604

mqudsi opened this issue Jun 16, 2018 · 2 comments

Comments

@mqudsi
Copy link
Contributor

mqudsi commented Jun 16, 2018

I don't see why the HashMap.entry(..) method

pub fn entry(&mut self, key: K) -> Entry<K, V>

requires that the lookup parameter key be of type K and not some type Q where K: Borrow<Q>, akin to HashMap.get(..):

pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V> 
where
    K: Borrow<Q>,
    Q: Hash + Eq, 

Given a HashMap<String, Foo>, just as a lookup can be performed with an &str parameter, it should be possible to obtain a HashMap::Entry<K, V> without requiring a full-blown instance of K be passed in to .entry(...).

i.e. the following code should work:

use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();

    map.insert("Foo".to_owned(), "Bar".to_owned());

    {
        // read-only reference to the result:
        let bar = map.get("Foo");
        assert!(bar.is_some());
    }

    {
        // why should this not be allowed?
        let bar = map.entry("Foo");
    }
}

Which currently returns the following:

error[E0308]: mismatched types
  --> ./test.rs:16:29
   |
16 |         let bar = map.entry("Foo");
   |                             ^^^^^
   |                             |
   |                             expected struct `std::string::String`, found reference
   |                             help: try using a conversion method: `"Foo".to_string()`
   |
   = note: expected type `std::string::String`
              found type `&'static str`

error: aborting due to previous error
@jonas-schievink
Copy link
Contributor

@Mark-Simulacrum
Copy link
Member

Closing as a duplicate of those discussions (and others, probably). Thanks for filling such a detailed issue!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants