以下不编译:
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/