从这一行开始:
fn b<A>(a: A, b: Copy + Into<A>) {}
我收到错误 non-Send/Sync additional trait
,指向Into<B>
少量。如果我删除它,它就会编译。如果我更改定义以采用满足这两个特征的附加类型参数,它也会编译。
fn a<A, B: Copy + Into<A>>(a: A, b: B) {}
最佳答案
请注意,完整的错误消息如下:
error[E0225]: only Send/Sync traits can be used as additional traits in a trait object
--> src/main.rs:1:25
|
1 | fn b<A>(a: A, b: Copy + Into<A>) {}
| ^^^^^^^ non-Send/Sync additional trait
此错误消息并未说明是否 Into<A>
实现Send
或Sync
;据说这个特质 Into<A>
本身不是这些特征中的任何一个。
编译器告诉您这一点是因为编译器假设您故意尝试创建具有多个特征的特征对象。
特征对象的典型示例是
Box<Trait>
之类的东西或&Trait
。您碰巧在特征本身之前编写了没有任何间接的代码,这是不支持的(至少在今天的 Rust 中不支持),但编译器将您的代码视为您的类型声明b: Copy + Into<A>
是一个trait对象,然后发现做出这样的假设后出现的问题。您可以在the book中阅读有关特征对象的更多信息。
如果您编写的代码的特征对象中仅包含一个特征,例如
b: std::fmt::Debug
,那么编译器会给你一个不同的错误:error[E0277]: the trait bound `std::fmt::Debug + 'static: std::marker::Sized` is not satisfied --> src/main.rs:1:15 | 1 | fn b<A>(a: A, b: std::fmt::Debug) {} | ^ `std::fmt::Debug + 'static` does not have a constant size known at compile-time | = help: the trait `std::marker::Sized` is not implemented for `std::fmt::Debug + 'static` = note: all local variables must have a statically known size
无论如何,在今天的 Rust 中,你通常不能将多个特征放入单个“特征对象”中。但有一种特殊情况:您当前可以使用 Send
和/或 Sync
作为特征对象中的附加特征。
因此编译器告诉您您尝试使用 Into<A>
作为特征对象中的附加特征是无效的,因为你只能有 Send
或Sync
作为附加特征,并且 Into<A>
不是其中任何一个。
关于rust - 为什么 `Into` 没有发送/同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45787322/