Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 574
AlgoQ Avatar asked Mar 15 '26 22:03

AlgoQ


1 Answers

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.

like image 111
Julius Kreutz Avatar answered Mar 19 '26 00:03

Julius Kreutz