简体   繁体   中英

Rust: Can not implement copy trait for struct

We have the following situation:

#[derive(Debug, Clone, PartialEq)]
pub struct Bar{
pub name: String,
pub anotherbar: Box<Option<Bar>>,
pub customenum: Option<Vec<Enum>>,
pub yesno: bool,
}

#[derive(Debug, Clone, Copy)]
pub struct foo {
pub name: String,
pub vector: Vec<bar>,
pub tuple: Vec<(u8, Bar)>,
}

and get the error message:

error[E0204]: the trait `Copy` may not be implemented for this type
   --> src/types.rs:459:24
    |
459 | #[derive(Debug, Clone, Copy)]
    |                        ^^^^
460 | pub struct Deck{
461 |     pub name: String,
    |     ---------------- this field does not implement `Copy`
462 |     pub commander: Vec<Card>,
    |     ------------------------ this field does not implement `Copy`
463 |     pub library: Vec<(u8, Card)>,
    |     ---------------------------- 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; 1 warning emitted

For more information about this error, try `rustc --explain E0204`.

I want to use the struct bar in a parallelization situation, where multiple requests add to the tuple field.

Can anyone help and explain?

Thanks and happy holidays.

Copy indicates "Types whose values can be duplicated simply by copying bits." (As a practical matter, Copy also strongly implies that copying the type is very cheap and so can be done implicitly.) Vec and String cannot be copied this way due to their internal buffers. They are both Clone (in the case of Vec , only when its contents are also Clone ). Clone means that a copy is possible, but must be done explicitly using the .clone() call.

I want to use the struct bar in a parallelization situation, where multiple requests add to the tuple field.

This sounds like you're trying to create shared mutable state. You should first carefully consider if this is what you really want. Typically you would instead do work in parallel and then collect all the data together at the end. That way the parallel activities don't interfere with each other. But if they must work together, then you'll need to use Mutex and other tools to provide thread-safety.

In either case, Copy wouldn't help you there, since that would create independent copies of the struct, which seems the opposite of what you're describing.

For more on Copy , see the docs explaining it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM