是否可以创建一个类型别名,该别名在函数的泛型类型上具有特征界限?

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

此代码:

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

产量error E0122(在较新版本的 Rust 中,它只是一个警告):

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.

是否可以创建一个包含函数指针特征要求的类型别名?显然编译器告诉我类型不对,但不知道是否还有我没有想到的函数选项。

目前看来不可能,也没有解决方法。

对于从 Rust 1.47.0 开始仍然对此感到好奇的人来说,它仍然是不可能的,但看起来你会收到一条带有描述和建议替代方案的不错的小警告消息。 例如

pub type PublishQueue<T: From<Message>> = (tokio::sync::mpsc::Sender<T>);

产量

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>;
|