如何克隆其中包含结构项的向量(生锈)?

How to clone a vector with struct items in it (rust)?

如何使用 Rust 中的结构项克隆向量。

我试过 .to_vec() 它,但似乎我做不到,因为我正在使用结构。

struct Abc {
    id: u32,
    name: String
}

let mut vec1: Vec<Abc> = vec![];

let item1 = Abc {
    id: 1,
    name: String::from("AlgoQ")
}

vec1.push(item1)

let vec2 = vec1.to_vec();

错误:

the trait bound `blabla::Abc: Clone` is not satisfied
the trait `Clone` is not implemented for `blabla::Abc`rustc(E0277)

要克隆 Vec Vec 中的 Type 还必须实现 Clone 特性。 最简单的方法是使用 derive macro as seen here.

在您的示例中,您只需在 Abc 结构上方添加 #[derive(Clone)]

您可以像对基元一样对结构对象执行此操作,但向量元素的结构必须实现 Clone 特征才能使向量可克隆。

正如编译器所说

你可以使用#[derive()]macro轻松实现trait,除非你不想使用自定义实现,如下

#[derive(Clone)]
struct Abc {
    id: u32,
    name: String
}

fn main(){
    let mut vec1= vec![];

    let item1 = Abc {
        id: 1,
        name: String::from("AlgoQ"),
    };
    vec1.push(item1);

    let vec2 = vec1.clone();
    
}

Demo