4

I have a struct similar to this:

struct Foo<'a> {
    callbacks: Vec<&'a FnMut(u32)>,
}

I want to call each callback, but my attempt doesn't work:

fn foo(&mut self) {
    for f in &mut self.callbacks {
        (*f)(0);
    }
}

I get this error:

error: cannot borrow immutable borrowed content `**f` as mutable

I also tried iter_mut() but I get the same error.

someguy
  • 7,144
  • 12
  • 43
  • 57

1 Answers1

5

FnMut takes a mutable receiver, so you must have a mutable reference to call it:

struct Foo<'a> {
    callbacks: Vec<&'a mut FnMut(u32)>,
}
malbarbo
  • 10,717
  • 1
  • 42
  • 57
  • Thanks. To be honest I tried that at one point, but had my doubts because of another error (now fixed) and also because it looked strange. Where can I learn more about receivers? – someguy Jul 12 '16 at 14:50
  • Receiver is the name used for the `self` parameter in the description of `Fn`, `FnMut` and `FnOnce` traits. You can read about the self parameter in [the book](https://doc.rust-lang.org/book/method-syntax.html). – malbarbo Jul 12 '16 at 14:57
  • Ok, let me rephrase. What is `self` in the context of a closure? Is it the enclosing environment? – someguy Jul 12 '16 at 14:59
  • 1
    Sorry for my confusion. For a closure, yes, self is the context of the closure. You can also implement `FnMut` trait for any struct (although it is not stable), in this case, `self` is a mutable reference to a instance of the struct, like in others trait implementations. – malbarbo Jul 12 '16 at 15:04