'How to get value from HashMap or create new one in Rust

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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source