0

I have following struct:

pub struct Foo {
    bar: Bar, // bar is another struct defined by me
    member: u8 // <-- this variable needs to be changed by `bar` struct
}

impl foo {
    pub fn call_bar_function(&mut self) {
        self.bar.bar_function(); // <-- I want to pass "foo" here as mutable
    }
}

bar_function() needs to change some fields of struct Foo or call one of its functions. But to do that I need reference of Foo in bar_function function, but I cannot figure out how to accomplish that.

I have tried this but its giving me an error:

--> src\foo.rs:40:38
   |
40 |         self.bar.bar_function(&mut self);
   |         -------- ------------------- ^^^^^^^^^ second mutable borrow occurs here
   |         |        |
   |         |        first borrow later used by call
   |         first mutable borrow occurs here

Is there a nice "Rustean" way of doing what I am trying to accomplish?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Ach113
  • 1,775
  • 3
  • 18
  • 40
  • You cannot do that: this code is unsafe because `bar` can make itself invalid by modifying its container. Please add more information, so that we can help you to solve your issue. Why does `bar` need a mutable reference to `foo` is an important piece of information, for example. – Boiethios Feb 10 '20 at 14:54
  • @Boiethios, ok I have updated the original post. I have a parameter in `foo` that I need to change through `bar`. I guess I could just pass it as mutable, but this question just popped in my mind and wanted to ask. – Ach113 Feb 10 '20 at 15:04
  • 1
    Yes, you must pass a reference to the member that you actually want to change, and that's ok. – Boiethios Feb 10 '20 at 15:05

0 Answers0