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/

相关文章:

c++ - vector 成员被重置且不可访问

c++ - Typedef vector 迭代器

c - 分配给指针的结构数组。发生了什么?

rust - 真或假

rust - 是否有从 Rust 的 Ordering::* 到整数的内置转换?

c++ - 使用什么数据结构来快速存储文本文件,其中有变量号。行数和变量号子元素的快速,在 C++ 中?

c++ - 将局部 vector 复制到 map 中某个键的值时遇到段错误

c - 在 C 中传递结构数组的元素

c - 从标准输入将整数读入 ADT

types - 如何避免无约束类型参数错误