簡體   English   中英

Rust:無法實現結構的復制特征

[英]Rust: Can not implement copy trait for struct

我們有以下情況:

#[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)>,
}

並得到錯誤信息:

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`.

我想在並行化情況下使用 struct bar,其中多個請求添加到元組字段。

誰能幫忙解釋一下?

謝謝,節日快樂。

Copy表示“可以簡單地通過復制位來復制其值的類型”。 (實際上, Copy還強烈暗示復制類型非常便宜,因此可以隱式完成。) VecString由於它們的內部緩沖區,不能以這種方式復制。 它們都是Clone (在Vec的情況下,只有當它的內容也是Clone時)。 Clone意味着可以進行復制,但必須使用.clone()調用顯式完成。

我想在並行化情況下使用 struct bar,其中多個請求添加到元組字段。

這聽起來像您正在嘗試創建共享可變 state。 您應該首先仔細考慮這是否是您真正想要的。 通常,您會改為並行工作,然后在最后收集所有數據。 這樣並行活動就不會相互干擾。 但是如果它們必須一起工作,那么您將需要使用 Mutex 和其他工具來提供線程安全。

在任何一種情況下, Copy都不會幫助您,因為這會創建結構的獨立副本,這似乎與您所描述的相反。

有關Copy的更多信息,請參閱解釋它的文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM