'How to store the context of users in HashMap?
My program is processing commands from different users. Each user has its own state that is modified by the commands he issues.
I use a HashMap to store the state of the users:
let mut states = HashMap::new();
A state is a struct:
pub struct State {
// details omitted
}
The program looks like this:
// loop
// current user is identified by 1st char of command
current_user = command[0..1].to_string()
match states.get(¤t_user) {
Some(&state) => {
println!("Switching User...");
current_state = state;
}
_ => {
println!("Creating User...");
current_state = State{...details omitted...};
states.insert(current_user, current_state);
}
}
// execute command in the State of the user
But I get the following error.
error[E0507]: cannot move out of a shared reference
42 | match states.get(¤t_user) {
| ^^^^^^^^^^^^^^^^^^^^^^^^
43 | Some(&state) => {
| ----
| |
| data moved here
| move occurs because `state` has type `Repository`, which does not implement the `Copy` trait
See Playground.
How can the program be fixed ? Do I need to use another structure than a HashMap ?
Solution 1:[1]
The trick is to use states.entry(..).or_insert(..) instead of states.get()...
The code is actually simpler (see playground)
current_state = states.entry(current_user)
.or_insert(State{v: String::from("P")});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pierre Carbonnelle |
