I have a map: HashSet<String, String>
and want to conditionally mutate each of the values.
I want to lookup the new values in the same HashSet
that I am mutating.
How can I do it without borrow checker problems?
fn main() {
let mut map = std::collections::HashMap::new();
map.insert("alien".to_string(), "".to_string());
map.insert("covid".to_string(), "virus".to_string());
map.insert("mammal".to_string(), "animal".to_string());
map.insert("cat".to_string(), "mammal".to_string());
map.insert("lion".to_string(), "cat".to_string());
println!("{:#?}", map);
// Replace values by lookup in self
loop {
let mut done = true;
for (key, val) in map {
if let Some(new) = map.get(val) {
if let Some(old) = map.insert(key.clone(), new.clone()) {
if &old != new {
done = false;
}
}
}
}
if done {
break;
}
}
let mut result = std::collections::HashMap::new();
result.insert("alien".to_string(), "".to_string());
result.insert("covid".to_string(), "virus".to_string());
result.insert("mammal".to_string(), "animal".to_string());
result.insert("cat".to_string(), "animal".to_string());
result.insert("lion".to_string(), "animal".to_string());
println!("{:#?}", result);
assert_eq!(map, result);
}