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 thatu32
does not implementFoo
. 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.
At this time, it does not seem to be possible and no workarounds exist.
For anyone still curious about this as of Rust 1.47.0 it is still not possible but it looks like you get a nice little warning message with a description and suggested alternative. e.g.
pub type PublishQueue<T: From<Message>> = (tokio::sync::mpsc::Sender<T>);
yields
note: `#[warn(type_alias_bounds)]` on by default
help: the bound will not be checked when the type alias is used, and should be removed
|
| pub type PublishQueue<T> = sync::mpsc::Sender<T>;
|
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With