vector - 如何创建 Vec<Struct> 并将其附加到 Vec<Struct>?

标签 vector struct rust

以下不编译:

struct A {
    f: u16,
}

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

但是编译器的信息似乎让我走上了错误的道路:

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` 

编辑代码以调用 append关于 a 的引用:

v.append(&mut a);

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

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`

不应该append正在寻找 Vec 的元素?它似乎在寻找 Vec本身。然而,我相信我正在为 Vec 进行正确的创建。持有 A 类型的元素.来自 Rust 书:

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 )

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

最佳答案

我想有人可能在评论中说过这个,但是 append 通过将它们移动到 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);

关于vector - 如何创建 Vec<Struct> 并将其附加到 Vec<Struct>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54154945/

相关文章:

macos - Rust cargo dylib 说明

rust - 递归闭包作为函数参数 “cannot infer an appropriate lifetime due to conflicting requirements”

r - 合并数据框和命名向量

c++ 在已知位置插入 vector

C++ 将结构成员作为参数传递

在 C 中创建具有三个属性的结构数组的概念

rust - 逗号分隔的syn::Idents列表

C++ - 在需要 Iterator 类型的 vector (或其他容器)构造函数中使用数组/指针。这怎么可能?

c++ - C++ vector 的 size() 和 capacity()

c - 访问结构成员时出现段错误