Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create and append to a Vec<Struct>?

The following does not compile:

struct A {
    f: u16,
}

fn main() {
    let v: Vec<A> = Vec::new();
    let a = A { f: 42 };
    v.append(a);
}

But the compiler message seems to be leading me down the wrong path:

error[E0308]: mismatched types
 --> src/main.rs:8:14
  |
8 |     v.append(a);
  |              ^ expected mutable reference, found struct `A`
  |
  = note: expected type `&mut std::vec::Vec<A>`
             found type `A` 

Editing the code to call append on a reference to a:

v.append(&mut a);

Also fails to compile, but with a surprising (to me) message:

error[E0308]: mismatched types
 --> src/main.rs:8:18
  |
8 |         v.append(&mut a);
  |                  ^^^^^^ expected struct `std::vec::Vec`, found struct `A`
  |
  = note: expected type `&mut std::vec::Vec<A>`
             found type `&mut A`

Shouldn't append be looking for an element of the Vec? It appears to be looking for a Vec itself. Yet, I believe I'm following the proper creating for a Vec holding elements of type A. From the Rust book:

To create a new, empty vector, we can call the Vec::new function, as shown in Listing 8-1.

let v: Vec<i32> = Vec::new();

(https://doc.rust-lang.org/book/ch08-01-vectors.html)

I have successfully used Vec<String> using the same pattern I'm attempting here, but I'm clearly misunderstanding something quite fundamental.

like image 511
JawguyChooser Avatar asked Dec 12 '25 11:12

JawguyChooser


1 Answers

I think someone may have said this in the comments, but append appends all the elements of another vector into this one by moving them into Self, I think you're trying to push(a) onto your vec

Details: https://doc.rust-lang.org/rust-by-example/std/vec.html

let mut xs = vec![1i32, 2, 3];
println!("Initial vector: {:?}", xs);

// Insert new element at the end of the vector
println!("Push 4 into the vector");
xs.push(4);
println!("Vector: {:?}", xs);
like image 115
Brandon Ross Pollack Avatar answered Dec 15 '25 13:12

Brandon Ross Pollack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!