Assign ref of empty vec in match

let l = match result_map.get("AOA").unwrap().get(key) {
            Some(val) => val,
            None => {
                &Vec::new()
            },
        };

result_map is a &HashMap<String, HashMap<String, Vec>.

When the key is not in the 2nd map, it should return empty Vec. (I don't need to insert it on the map)

But compiler said "temporary value dropped while borrowed".

How could I fix this? Any help would be appreciated.

Please give a reproducible example so we don't have to guess at your types. e.g. what type are you storing in Vec?

One way to solve it is to declare a static variable and return its reference.

1 Like

Use a shared slice (&[]), instead of a reference to a Vec. As a bonus, those also implement Default (yielding an empty slice).

    let l = result_map
        .get("AOA")
        .unwrap()
        .get(key)
        .map(Vec::as_slice)
        .unwrap_or_default();
2 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.