Passing a field of struct to a mutable function

Hello!
I have a problem with passing to a function (as mutable). I would like pass a struct (component, field of struct) to function - where the struct be update.

How to fix it?

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=936c1e6551de2cd2489be1a11d5ff137

I must passing as &Arc<Mutex> because I use Tokio.

Please help me.

In Rust &mut means two things: mutable and exclusive. In this case exclusivity prevents this from working.

&mut self means exclusive access to all of self, including self.stat. Therefore, it forbids from passing self.stat as any other argument.

You can:

  • stop using &mut self and make it a static function that takes only fields it needs.
  • use &self instead of &mut self, and do locking inside update

@mhanusek

To illustrate this approach:

  pub fn process(self_mutex: &Arc<Mutex<Self>>) {
      let mut mutex = self_mutex.lock().unwrap();
-     mutex.update(&mut mutex.stat);
+     Self::update(&mut mutex.stat);
  }

- pub fn update(&mut self, s: &mut Stat) {
+ pub fn update(s: &mut Stat) {
      println!("update");
      // update s
      let temp = s.c + 1;
      s.c = temp;
  }

Rust Playground

1 Like

Another question is, why do MainStuct::update ever need receiving field of self as argument? Can't it operate directly on &mut self?

1 Like

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.