Reputation: 177
How to push an item (struct type) from vector1 to vector2 in Rust? Can someone help me?
let mut vec1: Vec<Struct1> = vec![];
let item1 = Struct1 {
id: 1,
name: "AlgoQ".to_string()
};
vec1.push(item1);
let mut vec2: Vec<Struct1> = vec![];
vec2.push(&vec1[0]);
vec1.pop();
Error:
error[E0308]: mismatched types
--> src/test4.rs:17:15
|
17 | vec2.push(&vec1[0]);
| ^^^^^^^^
| |
| expected struct `Struct1`, found `&Struct1`
| help: consider removing the borrow: `vec1[0]`
Upvotes: 0
Views: 492
Reputation: 382150
Your item can't be at both place. You have to either
vec2.push(vec1.remove(0));
Here, as you also want to pop from the first vector, you may directly do
if let Some(item) = vec1.pop() {
vec2.push(item);
}
But be careful that pop
removes at the end, not at index 0
so your snippet is a little obscure regarding your exact intent.
vec2.push(vec1[0].clone());
Now, if you really want the item to be, conceptually, at two places, you may store references (ie &Struct1
) or indexes in your second vec.
Upvotes: 1