nat*_*ore 7 generics function-pointers traits rust type-alias
这段代码:
pub type Foo<T: Read> = fn(bar: T);
Run Code Online (Sandbox Code Playgroud)
产生错误 E0122(在较新版本的 Rust 中,这只是一个警告):
已尝试向类型别名添加通用约束。这个约束完全被忽略了。为了向后兼容,Rust 仍然允许这样做并带有警告。考虑下面的例子:
Run Code Online (Sandbox Code Playgroud)trait Foo {} type MyType<R: Foo> = (R, ()); fn main() { let t: MyType<u32>; }我们能够声明一个类型为 的变量
MyType<u32>,尽管事实上u32它没有实现Foo。因此,应该避免将泛型约束与类型别名一起使用。
是否可以创建一个包含对函数指针的特征要求的类型别名?显然,编译器告诉我没有类型,但不知道是否还有其他我没有想到的函数选项。
小智 8
对于任何仍然对此感到好奇的人来说,从 Rust 1.47.0 开始,这仍然是不可能的,但看起来你会收到一条很好的小警告消息,其中包含描述和建议的替代方案。例如
pub type PublishQueue<T: From<Message>> = (tokio::sync::mpsc::Sender<T>);
Run Code Online (Sandbox Code Playgroud)
产量
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>;
|
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4095 次 |
| 最近记录: |