Skip to content

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

@mqudsi

Description

@mqudsi

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions