Search code examples
vectorrustclonetraits

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


How to clone a vector with struct items in Rust.

I've tried to .to_vec() it, but it seems that I can't because I'm using structs.

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();

Error:

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

Solution

  • To clone a Vec the Type inside the Vec also has to implement the Clone trait. The easiest way to do this is to use the derive macro as seen here.

    In your example you'd just have to add #[derive(Clone)] above your Abc struct.