簡體   English   中英

如何使特征(以及實現它的結構)可克隆?

[英]How to make a trait (and a struct implementing it) clonable?

編譯如下代碼,出現如下錯誤。

error[E0277]: the trait bound `dyn T: std::clone::Clone` is not satisfied
 --> src/main.rs:3:21

請幫我修復代碼。

操場

trait T {}

#[derive(Clone)]
struct S1 { val: isize, nd:B ox<dyn T> }

#[derive(Clone)]
struct S2 { val: isize }

impl T for S1 {}
impl T for S2 {}

fn main() {
   let x2 = S2 { val: 2 };
   let x1 = S1 { val: 1, nd: Box::new(x2) };
   let x1 = x1.clone();
}

編譯器告訴您Box<dyn T>不滿足 trait Clone

為了解決這個問題,你可以做的是:

trait T: Clone {}

這將強制T所有實現者也實現Clone

這解決了一個問題,但是在這樣做之后你會看到一個新的錯誤,不允許你構造一個 trait 對象。

error[E0038]: the trait `T` cannot be made into an object
 --> /Users/mihir/fquicktest/data/user_data/instances/so_rust_q.rs:3:21
  |
3 | struct S1{val:isize,nd:Box<dyn T>,}
  |                     ^^^^^^^^^^^^^ the trait `T` cannot be made into an object
  |
  = note: the trait cannot require that `Self : Sized`

error: aborting due to previous error

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

我真的建議您閱讀rustc --explain E0038 它的文檔記錄得非常好,並且會向您解釋無法創建 trait 對象的情況。

此外,要解決此問題,您可以使用dyn-clone

更新您的代碼:

use dyn_clone::DynClone;

trait T: DynClone {}
dyn_clone::clone_trait_object!(T);

#[derive(Clone)]
struct S1 {
    val: isize,
    nd: Box<dyn T>,
}
#[derive(Clone)]
struct S2 {
    val: isize,
}

impl T for S1 {}
impl T for S2 {}

fn main() {
    let x2 = S2 { val: 2 };
    let x1 = S1 {
        val: 1,
        nd: Box::new(x2),
    };
    let x1 = x1.clone();
}

dyn_clone文檔上有一些示例可能會提供更多幫助。

暫無
暫無

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

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