Closed
Description
I want to check if a hashmap contains a key, and if it does not, I want to either return from the function early, or insert a value for that key, based on some logic.
fn main() {
let mut map = std::collections::HashMap::<u32, u32>::new();
let key = 9;
// works, but triggers the `map_entry` lint
if !map.contains_key(&key) {
let value = match get_value() {
Ok(value) => value,
Err(_) => {
println!("error");
return;
}
};
map.insert(key, value);
}
// does not work, since you can't return from the outside function in a closure
map.entry(key).or_insert_with(|| {
match get_value() {
Ok(value) => value,
Err(_) => {
println!("error");
return;
}
}
});
}
fn get_value() -> Result<u32, ()> {
// in my actual code this function is more expensive, so moving it to before checking if the key exists is undesired
Ok(5)
}
Clippy complains that that using map.entry(key)
will be more efficient, but I suspect this is a false positive in this case, since moving the return
to inside the closure of .or_insert_with()
will just return from the closure rather than the function.