如何创建并附加到 Vec<Struct>?

Jaw*_*ser 6 struct vector rust

以下内容无法编译:

struct A {
    f: u16,
}

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

但编译器消息似乎引导我走上了错误的道路:

struct A {
    f: u16,
}

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

编辑代码以调用append对 的引用a

v.append(&mut a);
Run Code Online (Sandbox Code Playgroud)

也无法编译,但有一个令人惊讶的(对我来说)消息:

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` 
Run Code Online (Sandbox Code Playgroud)

不应该append寻找 的元素吗Vec?它似乎在寻找自己Vec。然而,我相信我正在遵循正确创建Vectype 的保持元素的方法A。来自《铁锈》一书:

要创建一个新的空向量,我们可以调用该Vec::new函数,如清单 8-1 所示。

let v: Vec<i32> = Vec::new();
Run Code Online (Sandbox Code Playgroud)

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

我已经成功地使用了Vec<String>我在这里尝试的相同模式,但我显然误解了一些非常基本的东西。

Bra*_*ack 16

我想有人可能在评论中说过这一点,但是追加将另一个向量的所有元素移动到 Self 中,将它们附加到这个向量中,我认为你正在尝试将它们添加到push(a)你的 vec 上

详细信息: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);
Run Code Online (Sandbox Code Playgroud)