How do I express a constraint like
fn<F: 'static> apply_to_foos(f: F)
where
for<'a> F: fn(&'a mut Foo) -> impl Future<Output = Bar> + 'a
{
...
}
(The above expression doesn't work because constraints can't have impl in them)
If this isn't possible, what can I do instead?
Using a heap allocated trait object we already can express that constraint with current compiler featuers (Rust 1.61).
Maybe this is already what we want to do, but for fun and games, let's say we want to use compile time polymorphy:
It is concievable that a future version of Rust would just allow us to replace the
dynin the above signature and replace it with animpl, while dropping theBoxaltogether. FYI: TheBoxis not needed for above signature to compile, but most real world usecase would require it in order to keep the trait object alive long enough.Using an
implhere would require the compiler to supporttraits which can in turn depend on othertraits. Rust cannot do that, buttraits can depend on concrete types. Let's introduce a typeOinto our signature.This almost does what we want, but we have no way to transfer the lifetime requirement of
'atoO, since&'ais local to the constraint ofF. We can factor out the entire constraint into its own trait however:with
FooToBarbeing declared like this (for example):Wether avoiding the heap allocation is worth the code bloat likely depends on your domain. I'd probably stick with the
Box<dyn>version most of the time.