0

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]` 

1 Answer 1

1

Your item can't be at both place. You have to either

  1. remove the item from the source vector:
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.

  1. or clone the item (assuming it can be cloned)
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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.