【发布时间】:2021-04-25 08:50:25
【问题描述】:
我是 Rust 特征的新手,所以这可能是由于对超特征、dyn 或其他任何东西的误解。我正在尝试在枚举中使用特征对象:
- 将特征绑定在可用于枚举的此元素的具体类型上
- 确保枚举仍然可以派生
Copy
最小的例子(在 Rust playground 上编译失败并出现相关错误)是:
#[derive(Copy)]
enum Foo {
A,
B(dyn MyTraitWhichIsCopy),
}
trait MyTraitWhichIsCopy: Copy {}
错误是:
error[E0204]: the trait `Copy` may not be implemented for this type
--> src/lib.rs:1:10
|
1 | #[derive(Copy)]
| ^^^^
...
4 | B(dyn MyTraitWhichIsCopy),
| ---------------------- this field does not implement `Copy`
|
= note: this error originates in a derive macro (in Nightly builds, run with -Z macro-backtrace for more info)
error: aborting due to previous error
For more information about this error, try `rustc --explain E0204`.
在调用 rustc --explain E0204 之后,我注意到以下内容,这可能是我遇到问题的地方:
The `Copy` trait is implemented by default only on primitive types. If your
type only contains primitive types, you'll be able to implement `Copy` on it.
Otherwise, it won't be possible.
有没有办法完成我想做的事情?
【问题讨论】:
标签: rust trait-objects