HashMap insert lifetimes

  let session = valid_session(cookies);
  let mut map = std::collections::HashMap::new();
  match session {
     None => {},
     Some(s) => {
         let user = s.user().clone();
         map.insert("user", user.as_str());
     },
  };

map.insert("title", "Title");

Error:

     |
  56 |             map.insert("user", user.as_str());
     |                                ^^^^ borrowed value does not live long enough
  57 |         },
     |         - `user` dropped here while still borrowed
  ...
  60 |     map.insert("title", "Title");
     |     --- borrow later used here

Just trying to insert a str into a HashMap. Anyone know how to do it?

The value type for the HashMap shouldn't be &'_ str here but String, so that you give the user itself to the hashmap when inserting it, rather than borrow it.

BTW: String internally holds its data by reference.

The difference between String and &str is not whether data is passed by reference, but whether it's owned and can be used anywhere in the program, or it's temporary and will be gone before the next }.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.