Search code examples
genericsrustfunction-pointerstraitstype-alias

Is it possible to create a type alias that has trait bounds on a generic type for a function?


This code:

pub type Foo<T: Read> = fn(bar: T);

yields error E0122 (in newer versions of Rust, it is only a warning):

An attempt was made to add a generic constraint to a type alias. This constraint is entirely ignored. For backwards compatibility, Rust still allows this with a warning. Consider the example below:

trait Foo {}

type MyType<R: Foo> = (R, ());

fn main() {
    let t: MyType<u32>;
}

We're able to declare a variable of type MyType<u32>, despite the fact that u32 does not implement Foo. As a result, one should avoid using generic constraints in concert with type aliases.

Is it possible to create a type alias that contains trait requirements on a function pointer? Obviously the compiler is telling me no for types, but didn't know if there was another option for functions that I wasn't thinking of.


Solution

  • At this time, it does not seem to be possible and no workarounds exist.