Closed
Description
What it does
Optimize hashset (and possibly similar HashMap?) usage when the user first uses contains()
to check the non-existence of a value, followed by insertion.
Advantage
- Faster code
- Shorter code
Drawbacks
No response
Example
use std::collections::HashSet;
fn main() {
let mut vals = HashSet::new();
insert_if(&mut vals, 10);
}
fn insert_if(set: &mut HashSet<i32>, value: i32) {
if !set.contains(&value) {
set.insert(value);
println!("inserted {value:?}");
}
}
Could be written as:
fn insert_if(set: &mut HashSet<i32>, value: i32) {
if set.insert(value) {
println!("inserted {value:?}");
}
}