Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 381
nathansizemore Avatar asked Jun 17 '16 00:06

nathansizemore


2 Answers

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

like image 110
nathansizemore Avatar answered Nov 08 '22 22:11

nathansizemore


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>;
|
like image 5
Cameron Dart Avatar answered Nov 08 '22 23:11

Cameron Dart