Hi all.
Please look at this example:
struct Info {
thing: i32
}
enum StuffStatus {
V1(Option<Info>),
V2(Option<Info>),
V3,
V4(i32)
}
struct Stuff {
status: StuffStatus,
counter: usize
}
impl Stuff {
fn do_stuff(&mut self) -> Result<(), String> {
match &mut self.status {
StuffStatus::V1(info) => {
self.modify_something();
let informations = info.take().unwrap();
self.status = StuffStatus::V2(Some(informations));
Ok(())
}
_ => Err("no.".into())
}
}
fn modify_something(&mut self) {
self.counter += 1;
}
}
fn main() {
let mut s = Stuff {
status: StuffStatus::V1(Some(Info { thing: 1234 })),
counter: 0
};
s.do_stuff();
}
I get this error:
23 | match &mut self.status {
| ---------------- first mutable borrow occurs here
...
27 | self.modify_something();
| ^^^^^^^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
28 |
29 | let informations = info.take().unwrap();
| ----------- first borrow later used here
I don't understand why calling the method modify_something()
is a problem here. It uses its mutable reference &mut self
, does its thing that remains all inside self
, and that's it. Also, if I replace the line 27 with self.counter += 1
(i. e. the method content) the compiler compiles.
Maybe it is related to what I'm doing in lines 29 and 30? I'm just trying to change the variant from V1
to V2
while keeping the field content; I don't really need the Option
inside these variants, but I can't find a better way.
Thanks for any explanation!