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

标签 generics rust function-pointers traits type-alias

这段代码:

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 开始仍然对此感到好奇的人来说,它仍然是不可能的,但看起来你会收到一 strip 有描述和建议替代方案的不错的小警告消息。 例如

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

关于generics - 是否可以创建一个类型别名,该别名在函数的泛型类型上具有特征界限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37871267/

相关文章:

java - 通用类型解析 - 编译器步骤

c# - 自反类型参数约束 : X<T> where T : X<T> ‒ any simpler alternatives?

winapi - 使用Rust语言使用winapi SetClipboardData

rust - 是否可以为 `time::Duration` 之类的结构指定全局常量?

c - 这是将 va_arg 与函数指针一起使用的正确方法吗?

c++ - 可变参数模板函数确定函数指针返回类型

generics - Kotlin:为什么一元加/减无法从赋值推断泛型类型?

hashmap - 为什么 HashMap 需要加密安全的哈希函数?

c# - 如何从 C# 中的函数指针获取函数名称?

Java 泛型 : the type parameter T is hiding the type T