title: rust - methods as argument including a self reference
body: <p>I have the following problem:
  I have two structs A and B, A implements a method, which takes another method as argument. I then create an instance of A within B. I then call the method of A with a method of B as argument. However, the passed method of B contains self as argument, since I have to access some other fields of B within the passed method.</p>
  <p>My current plan would be to pass the method itself and self referencing an instance of B to the method in A. However, I struggle with the type definitions. I can hardcode the type of the second parameter to be B, however, I would like to keep it open, in case a struct C would also like to use the method in A. I therefore would like to set the type of the second parameter to the type of the struct, where the method in the first parameter is originating. Is there a way for achieving this? I was thinking about generics, however, I was not yet able to implement it.</p>
  <p>Edit: added a minimal example in rust playground. What bothers me about this code, is, that I want to get rid of the hard coded &amp;B in some_func_a, since this does not work with struct C.</p>
  <pre><code>struct A {}
  
  impl A {
      fn some_func_a(&amp;self, passed_fn: fn(&amp;B, i32), cur_self: &amp;B) {
          passed_fn(cur_self, 21);
      }
  }
  
  struct B {
      some_val: i32,
  }
  
  struct C {
      some_val: u32, // different field here than in B
  }
  
  impl B {
      fn call_fn_in_a(&amp;self, a: A) {
          a.some_func_a(B::some_func_b, self);
      }
  
      fn some_func_b(&amp;self, passed_val: i32) {
          println!(&quot;The value is {}, passed was {}&quot;, self.some_val, passed_val)
      }
  }
  
  impl C {
      fn call_fn_in_a(&amp;self, a: A) {
          // this line here breaks, since &amp;B is hard coded
          a.some_func_a(C::some_func_c, self);
      }
  
      fn some_func_c(&amp;self, passed_val: i32) {
          println!(&quot;this is a new function, val is {}, passed was {}&quot;, self.some_val, passed_val)
      }
  }
  
  fn main() {
      let a = A {};
      let b = B {
          some_val: 42,
      };
      
      let b = B {
          some_val: 42,
      };
      b.call_fn_in_a(a);
  }
  </code></pre>
  <p><a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2021&amp;gist=53ac44cb660d180b3c7351e394355692" rel="nofollow noreferrer">https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2021&amp;gist=53ac44cb660d180b3c7351e394355692</a></p>