I am trying to store some session information in a HashMap. I wrote a much simplifed example of the problem that I am having. So far this is the best that I was able to do.
use std::collections::HashMap;
struct Session {
last_number: f32,
//Other stuf
}
fn main() {
let mut sessions : HashMap<i32, Session> = HashMap::new();
for n in 0..10 {
let userid = 32; //This is obtained from the user
let number = 1.2; //This is obtained from the user
if !sessions.contains_key(&userid) {
let session = Session{last_number: 0.};
sessions.insert(userid, session);
}
let mut session = sessions.get_mut(&userid).unwrap();
session.last_number = number;
}
}
It does not look very nice. When the key is not found, I am querying, inserting and then querying again the map. I would like to reuse the session object built for insertion and avoid calling contains_key
. I think it should be enough with get_mut
as it returns an Option<V>
. ButI failed when trying make a change in this direction. The compiler/borrow checker was complaining and I was not able to solve it.
My questions are:
- Is it really a bad design or it does not matter for rust in terms of efficiency?
- How can I implement the other solution?