Current best practice for implementing Fn on a new or existing type

⚓ Rust    📅 2026-04-02    👤 surdeus    👁️ 5      

surdeus

I often want to build structs along the lines of

pub struct MyStruct< T: Fn(usize) -> Option<usize> >{ fn: T }

There's a natural way to think about this if, for example, you want T to be a hash map. But last I checked you can't implement Fn manually on any struct.

What's the current best-practice work around? Options I'm currently considering are

  1. Make a wrapper FnWrap around HashMap and implement something from the fn_traits crate on FnWrap< HashMap >.
  2. Write my own Fn trait and implement HashMap.

If option 1. is the best, then would it make sense to submit a PR for FnWrap to fn_traits (I can always post an issue on their repo). Thanks!

2 posts - 2 participants

Read full topic

🏷️ Rust_feed