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

Alg*_*goQ 1 clone vector traits 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();
Run Code Online (Sandbox Code Playgroud)

错误:

the trait bound `blabla::Abc: Clone` is not satisfied
the trait `Clone` is not implemented for `blabla::Abc`rustc(E0277)
Run Code Online (Sandbox Code Playgroud)

小智 7

要克隆Vec内部的类型,Vec还必须实现Clone特征。最简单的方法是使用派生宏,如此处所示。

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