Say we have the following:
trait Trait {}
struct A;
impl Trait for A {}
struct B;
impl Trait for B {}
Is there a good way of writing a helper function that will call a generic function which takes a type T: Trait and passes A and B as the generic parameter? i.e.:
fn helper<Args>(f: /* ??? */, args: Args) {
f::<A>(args);
f::<B>(args);
}
fn do_thing<T: Trait>() { }
helper(do_thing);
No, not directly, as Rust doesn't have higher-order types.
However, you can define your own trait with a generic method. Demo.
We don't have types or bounds that are higher-ranked over type generics so far, and even if we did it wouldn't apply to do_thing without larger language changes, as T would be unconstrained in the implementation of the Fn traits. (T would need to appear in the arguments.)
Also your code is inconsistent since do_thing doesn't take Args. (Rust also has no stable mechanism for "any number of args the closure may take", if that's what you were going for.)
Thanks! This ends up being pretty verbose but can probably be improved with a macro.