1

I am wondering what would be an elegant way to either get an existing value from a HashMap or create a new one and assign it to a variable.

I was thinking about something like this ...

struct Test {
    name: String,
    valid: bool
}

    let tests: HashMap<String, Test> = HashMap::new();

    let key = String::from("a");

    let test = match tests.get(&key) {
        Some(t) => t,
        None => {
            let t = Test {
                name: key,
                valid: false,
            };

           &t
        }
    };

This results to the expected error

error[E0597]: `t` does not live long enough
  --> src/main.rs:33:12
   |
33 |            &t
   |            ^^
   |            |
   |            borrowed value does not live long enough
   |            borrow later used here
34 |         }
   |         - `t` dropped here while still borrowed

A kind of workaround is to do this ...

    let t;
    let test = match tests.get(&key) {
        Some(node) => node,
        None => {
            t = Test {
                name: key,
                valid: false,
            };

           &t
        }
    };

It seems to me a little bit unhandy just to introduce the extra variable t in advance to be able to shift out the reference of the allocated structure for the case the instance of the structure is not found in the HashMap.

Is there a better way to do this?

Horowitzathome
  • 359
  • 3
  • 13
  • 6
    Assuming you want to add the entry into the map, consider the [`entry`](https://doc.rust-lang.org/std/collections/hash_map/struct.HashMap.html#method.entry) API, eg `let test = tests.entry(key).or_insert(Test { name: key, value: false });`. – eggyal Feb 19 '22 at 13:29
  • As an aside, it's a little odd to store a copy of the key in the value. Perhaps you're actually after a `HashSet` where the `Hash` impl for `Test` is based only on its `name` field? – eggyal Feb 19 '22 at 13:30
  • @eggyal this answered my question. If you want me to accept it as answer, please post it as answer, so that I am able to mark it as answer. – Horowitzathome Feb 19 '22 at 13:44
  • 1
    Does this answer your question? [How to lookup from and insert into a HashMap efficiently?](https://stackoverflow.com/questions/28512394/how-to-lookup-from-and-insert-into-a-hashmap-efficiently) – Chayim Friedman Feb 19 '22 at 23:34

0 Answers0