Reputation: 1019
Basically I am having hard time understanding why calling multiple methods on a mutable reference can cause the borrow checker to err. Example snippet:
use std::collections::HashMap;
struct MainState {
// The HashMap owns the values which is Ok.
queues: HashMap<String, Vec<String>>,
}
impl MainState {
fn new() -> Self {
Self {
queues: HashMap::new(),
}
}
fn get_queue(&mut self, session_id: &str) -> &mut Vec<String> {
// borrowing the first time explicitly
let queues = &mut self.queues;
let queue = queues.get_mut(session_id);
if queue.is_none() {
let queue = Vec::new();
// Multiple mutable error on the following lines. Why?
queues.insert(session_id.to_string(), queue);
queues.get_mut(session_id).unwrap()
} else {
queue.unwrap()
}
}
}
I can't figure out how to fix this code in an idiomatic acceptable way.
Upvotes: 0
Views: 33