How do I get this to compile?

You're trying to return a reference to a HashSet borrowed from a closure's environment. Unfortunately, the signature:

impl Fn(&K) -> &HashSet<V>

allows the returned value to borrow only from the key argument, but not from the environment. None of three current closure types allows to return a borrow from environment.

As a workaround, you can:

  • Return a custom struct,
  • Return an impl of a custom trait,
  • Return impl Fn(&K) -> Rc<HashSet<V>>. There is some overhead associated with Rc, but compared to the cost of search operation on the hashmap, this overhead shouldn't be noticable.

The note in the error message is really confusing. You should consider filing a bug.