I'm looking for a best practice for the insert-or-update
operation, because it is very commonly used, I think we need to optimize both its writing style and efficiency.
Assume the following scenario: I got a hashmap
let classes: HashMap(String, HashSet<String>) = HashMap::new()
which is used to store students and whos classes.
The data is expected to be in the following form:
{ key: "ClassA", value: {"Bob", "Marry", "Jack"}},
{ key: "ClassB", value: {"Lee", "Tom"}},
Now I got a new set of data of a student and his/her class, let's take:
{ name: "Alice", class: "ClassC"}
Since I'm not sure if the class already appears in the classes
HashMap, I need to figure out whether it exists first, if it is, I'm going to update the value, and if it's not, I'm going to add a new key->value
pair.
What's the correct way to do it with out any unnecessary move or copy? Based on other answers, I tried to use std::collections::hash_map::Entry
but I failed.
Thanks!