Why can't I use a `Copy` type in a union?

The following code:

#[derive(Clone, Copy)]
struct B<Element> {
    _marker: std::marker::PhantomData<Element>

union AOrB<Element> {
    a: (),
    b: B<Element>,

gives me this error:

error[E0740]: unions cannot contain fields that may need dropping
 --> src/lib.rs:8:5
8 |     b: B<Element>,
  |     ^^^^^^^^^^^^^
  = note: a type is guaranteed not to need dropping when it implements `Copy`, or when it is the special `ManuallyDrop<_>` type
help: when the type does not implement `Copy`, wrap it inside a `ManuallyDrop<_>` and ensure it is manually dropped
8 |     b: std::mem::ManuallyDrop<B<Element>>,
  |        +++++++++++++++++++++++          +

For more information about this error, try `rustc --explain E0740`.
error: could not compile `playground` due to previous error

The error says that B doesn't implement Copy, however, B does implement Copy. Am I missing something? Or is this a bug?

The #[derive] macro always adds the Copy bound to the type parameter. Implement Clone and Copy manually, like this.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.