How to get Item from Hashmap

use std::collections::HashMap;
pub struct A {}


pub struct B(HashMap<String, A>);

impl B {
    
    pub fn get(self, key: &String) -> Option<&A> {
        self.0.get(key)
//      ^^^^^^^^^^^^^^^ returns a reference to data owned by the current function
    }

}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0515]: cannot return reference to local data `self.0`
  --> src/lib.rs:10:9
   |
10 |         self.0.get(key)
   |         ^^^^^^^^^^^^^^^ returns a reference to data owned by the current function

For more information about this error, try `rustc --explain E0515`.
error: could not compile `playground` due to previous error

If you want to borrow the self.0 map as a reference, you'll have to borrow &self as a reference (Rust Playground):

use std::collections::HashMap;

pub struct A {}

pub struct B(HashMap<String, A>);

impl B {
    pub fn get(&self, key: &String) -> Option<&A> {
        self.0.get(key)
    }
}

By the rules of lifetime elision, the output reference will live as long as the &self reference (that is, the &B reference that you call the method on).

Also, it's considered a best practice to make key a &str instead of a &String if you aren't planning on writing to it. A &String reference will implicitly turn into a &str reference, and using &str allows you to call the method with string literals as well as runtime String objects.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.