title: How to store a callback in a struct that can change the struct's internal state?
body: <p>In one of my projects, I would like to store a function pointer used as a callback to change the state of a struct. I've tried different things, but always encountered errors.</p>
  <p>Consider the following situation (<a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2021&amp;gist=8112baa75783684f78c52e4a63b6ce17" rel="nofollow noreferrer">playground</a>):</p>
  <pre class="lang-rust prettyprint-override"><code>struct CallbackStruct {
      callback: fn(i32) -&gt; i32,
  }
  
  struct MainStruct {
      pub callback_struct: Vec&lt;CallbackStruct&gt;,
      pub intern_state: i32,
  }
  
  impl MainStruct {
      pub fn new() -&gt; MainStruct {
          let result = MainStruct {
              callback_struct: Vec::new(),
              intern_state: 0,
          };
          // push a new call back struct
          result.callback_struct.push(CallbackStruct{callback: result.do_stuff});
          
          return result;
      }
  
      pub fn do_stuff(&amp;mut self, i: i32) -&gt; i32 {
          self.intern_state = i * 2 + 1;
          self.intern_state
      }
  }
  
  fn main() {
      let my_struct = MainStruct::new();
  }
  </code></pre>
  <p>Here, I'm trying to keep a callback to the <code>MainStruct</code>, that can change it's internal state. This callback will only be stored by other structs owned by this main structure, so I don't think I'm having lifetimes issues - as long as the callback exists, the main struct does as well as it kind of own it.</p>
  <p>Now, I'm wondering if having such a callback (with the <code>&amp;mut self</code> reference) isn't a borrow of the main struct, preventing me from having multiple of them, or even keeping them?</p>
  <p>In the example, I'm keeping a <code>Vec</code> of the <code>CallbackStruct</code> because I may have different structs all having these kinds of callbacks.</p>
  <p>In c/c++, I can go with functions pointers, and I couldn't find a way to store such things in Rust.</p>
  <p>How would one implement such a thing?</p>