use std::collections::HashMap;
use std::collections::hash_map::Entry::*;
struct A {
map: HashMap<String, String>,
i: i32
}
impl A {
fn test(&mut self) {
match self.map.get("abc") {
None => {},
Some(x) => self.trigger(&x)
}
}
fn trigger(&mut self, x: &str) {
self.i += 1;
}
}
The code doesn't work because self.trigger
borrows self
mutably, while self.map.get
is keeping an immutable borrow of self
in scope.
Is there any way to make it work, given that I can make sure in the trigger
I don't modify self.map
?
I cannot make trigger
borrow self
immutably, as in Can I borrow self immutably for self.callbacks: Vec<Box<FnMut>>?
I'm using rustc 1.19.0-nightly.
The problem here is that the borrow checker does not know that
trigger
only changesself.i
. As far as the borrow checker knows, it might also changeself.map
, which would be unsafe.The solution is to tell the borrow checker more about what
trigger
changes.One way to do this is by moving everything that
trigger
needs to borrow mutablely into its own struct, and then implement trigger for that struct:see Rust Book: If Let if you haven't seen the awesome
if let
syntax it before.