I have a structure Struct
that optionally contains SubStruct
. SubStruct
contains a field.
I would like to call the modify
member method of Struct
, that calls the modify_field
member method of SubStruct
that modifies the field
field of SubStruct
This is different from other questions mentioned, as it is not modifying the field directly, but calling a member method that in turn modifies the field. Modifying the field directly has a shared solution I have seen.
struct SubStruct {
field: u32,
}
impl SubStruct {
fn modify_field(&mut self) {
self.field = 2
}
}
struct Struct {
sub: Option<SubStruct>,
}
impl Struct {
fn modify(&mut self) {
if let Some(ref mut sub) = self.sub { // no reference before Some
sub.modify_field();
self.do_something();
}
}
fn do_something(&self) {
}
}
fn main() {
let sub = Some(SubStruct{field: 1});
let mut structure = Struct{ sub };
structure.modify();
println!("{}", structure.sub.unwrap().field);
}
I've tried many variants with no luck, with my current version I am stuck with this error:
error[E0502]: cannot borrow `*self` as immutable because `self.sub.0` is also borrowed as mutable
--> src/main.rs:20:13
|
17 | if let Some(ref mut sub) = self.sub { // no reference before Some
| ----------- mutable borrow occurs here
...
20 | self.do_something();
| ^^^^ immutable borrow occurs here
21 | } | - mutable borrow ends here
As you can see, it seems to be related to self.do_something()
taking an immutable borrow of self
, where a mutable borrow of self
was already taken in the function parameter.