How to write where clause for closure with context

This is a follow up to this already answered question, except I don't think I can use the question here as my function here has context.

Consider the following example:

pub trait SillyTrait<T1> {
    fn silly(self);
}

pub fn silly2<T1, T2>(x : T1, y: T2) where T2 : SillyTrait<T1> {
    <T2 as SillyTrait<T1>>::silly(y);
}

pub fn silly3<T1>(f : impl Fn(T1, i64) -> i64, x : T1)
where typeof(f2) : SillyTrait<T1>
{
    let f2 = |y : i64| f(x, y);
    silly2(x, f2);
}

It's just typeof(f2) that I can't write here, but as silly3 seems valid (at least for some impls of SillyTrait) I should be able to write it I presume. But casting to an fn doesn't seem to work as f2 has context and writing a global function also won't work I don't think because I'll get all sorts of nasty race conditions if it's used at the same time (which Rust is supposed to check against) so I'm a bit lost about how to write this but I'm sure it's possible as it would be crazy for it not to be.

You can't do this yet, you can't reference types defined inside the function you are putting a where clause for.

You can manually desugar the closure and implement SillyTrait for that type. This will give you a type that you can name. You can see how to desugar closures in my blog on closures here:

Would it be possible to create an example that is a bit closer to your actual goal? Your current example has a generic trait SillyTrait<T1> where the type T1 is unused, then a function fn silly2<T1, T2>(x : T1, y: T2) where T2 : SillyTrait<T1> where the value x and type T1 are unused. And then a silly3 that does not make syntactic sense. It's hard to guess how you might achieve your goals when they are so well hidden.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.