I'm new to Rust traits, so this could be due to a misunderstanding of supertraits, dyn
or anything else. I'm trying to use a trait object in an enum to:
- Put a trait bound on the concrete types that can be used in this element of the enum
- Make sure that the enum can still derive
Copy
The minimal example (which fails to compile on Rust playground with the relevant error) is:
#[derive(Copy)]
enum Foo {
A,
B(dyn MyTraitWhichIsCopy),
}
trait MyTraitWhichIsCopy: Copy {}
The error is:
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`.
After invoking rustc --explain E0204
I noticed the following, which might be where I'm hitting problems:
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.
Is there a way to accomplish what I'm trying to do?