Specifying a FnMut() that takes an object implementing a trait?

I'm trying to write a struct where one of the fields holds a closure that takes as it's argument something that implements a specific trait (BufRead in my example). My attempt to define this is as so:

use std::io::BufRead;

pub struct ClosureHolder<T>
where
    T: FnMut(impl BufRead) -> Option<String>,
{
    closure: T,
}

However, I get the error message:

error[E0562]: impl Trait` not allowed outside of function and inherent method return types

If I replace the impl BufRead with a concrete type such as i64 this of course works. Is there a way to specify such a constraint based on a trait?

You can introduce a new type variable which implements BufRead and parameterize T on that:

pub struct ClosureHolder<T, B>
where
    T: FnMut(B) -> Option<String>,
    B: BufRead,
{
    closure: T,
}

e: You will need to put a PhantomData holding some kind of B in the struct, though; maybe phantom: PhantomData<fn(B)>.

3 Likes

Thanks!