struct Info {
num: u16,
}
struct InfoSet {
infos: Vec<Info>,
}
impl InfoSet {
fn get_info(&mut self, num: u16) -> &mut Info {
let info = self.infos.iter_mut().find(|i| i.num == num);
if let Some(info) = info {
info
} else {
self.infos.push(Info { num });
self.infos.last_mut().unwrap()
}
}
}
In get_info, the borrow checker complains that self.infos is borrowed mutable more than once, despite it can infer that info is None and therefore not borrowing anything.
Specifically, the fact to return info borrows self.infos for the whole function scope.
How can I refactor my code to avoid this error ?
fn get_info(&mut self, num: u16) -> &mut Info {
let position = self.infos.iter().position(|i| i.num == num);
if let Some(idx) = position {
&mut self.infos[idx]
} else {
self.infos.push(Info { num });
self.infos.last_mut().unwrap()
}
}
It works like this.
In this blog post you can see a very similar example at the top and how the rust team plans on fixing this limitation.
this is a limitation of the borrow checker, see problem case 3.
for certain (but not all) cases, using the nightly toolchain with the rustc flag -Zpolonius=next might pass the borrow checker, but the common fix (workaround?) in this case is using indices.