How to use the same struct instance in two functions

I'm really going super slow and very careful with this project. I see how even small step can cause the borrow checker to complain. How can I share the same struct with multiple functions and run operations on it?

    let system = System {

        x: HashMap::new(),

fn a(system:&System) {
      let System { mut x, .. } = system;
     // add something to x

  fn b(system:&System) {
      let System { mut x, .. } = system;
     // do stuff on x


error I'm getting

let System { &mut x, .. } = system;
   |             ------   ^ expected identifier
   |             |
   |             while parsing the fields for this pattern


38 |         let System { mut x, .. } = system;
   |                      ----------         ^^^^^^
   |                      |
   |                      data moved here
   |                      move occurs because `broker` has type `HashMap<String, Y>`, which does not implement the `Copy` trait

Looking at the error, its clear that it doesn't match the code you gave us. In the code, you're writing mut x without an ampersand, but the error has an ampersand. You cannot put an ampersand in that location.

Anyway, I'm guessing you're having trouble with getting mutable access to x in your a method. That's because it takes an immutable reference. There's no way to modify x through an immutable reference to System, no matter what you try to put in your let statement. Try this instead:

fn a(system: &mut System) {

Here, you make the reference itself mutable.

1 Like

Yeah sorry I was changing the code while creating this post. Thanks I'll try this.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.