title: Storing a closure in a HashMap
body: <p>To learn the Rust language, I'm taking an old C++ library I had lying around and trying to convert it to Rust. It used a lot of C++11 closures and I'm having some difficulty getting the concepts to translate.</p>
  
  <p>In C++ I had something like this:</p>
  
  <pre><code>// library.h
  struct Event {
      // just some data
  };
  
  class Object {
  public:
      // ...
      std::function&lt;void(Event&amp;)&gt;&amp; makeFunc(std::string&amp; s) {
          return m_funcs[s];
      }
      // ...
  private:
      // ...
      std::map&lt;std::string, std::function&lt;void(Event&amp;)&gt;&gt; m_funcs;
      // ...
  };
  
  // main.cpp using the library
  int main()
  {
      Object foo;
      foo.makeFunc("func1") = [&amp;]{
          // do stuff
      };
      return 0;
  }
  </code></pre>
  
  <p>The part that I'm having trouble with is properly storing the functions in a Rust HashMap collection. I tried this:</p>
  
  <pre><code>struct Event;
  
  struct Object {
      m_funcs : HashMap&lt;String, FnMut(&amp;Event)&gt;
  }
  
  impl Object {
      // send f as another parameter rather than try and return borrow
      // compiler was complaining
      fn makeFunc(&amp;mut self, s : &amp;str,f: FnMut(&amp;Event)) {
          self.m_funcs.insert(String::from_str(s), f); 
      }
  }
  </code></pre>
  
  <p>but it says <code>the trait core::marker::Sized is not implemented for the type 'for('r) core::ops::FnMut(&amp;'r CreateEvent)'</code></p>
  
  <p>This makes sense because <code>FnMut</code> is a trait, and therefore has no known size for the HashMap to make at compile time. So I figure that the hashmap would require an actual pointer rather than an abstract type. So I change it to this</p>
  
  <pre><code>struct Object {
      m_funcs : HashMap&lt;String, Box&lt;FnMut(&amp;Event)&gt;&gt;
  }
  
  impl Object {
      fn makeFunc(&amp;mut self, s : &amp;str, f: &amp;FnMut(&amp;Event)) {
          self.m_funcs.insert(String::from_str(s), Box::new(f));
      }
  }
  </code></pre>
  
  <p>now it says <code>the trait 'for('r) core::ops::Fn&lt;(&amp;'r CreateEvent,)&gt;' is not implemented for the type '&amp;for('r) core::ops::FnMut(&amp;'r CreateEvent)' [E0277]</code> at the insert. This error makes no sense to me at all. Can someone explain to me the proper way to store a reference to a non-escaping closure in a HashMap?</p>