这是一个非常简单的 2D Vec
尝试。我正在尝试将一个元素添加到顶级 Vec
中的最后一个条目:
fn main() {
let mut vec_2d = vec![vec![]];
if let Some(v) = vec_2d.last() {
v.push(1);
}
println!("{:?}", vec_2d);
}
我收到这个错误:
error[E0596]: cannot borrow `*v` as mutable, as it is behind a `&` reference
--> src/main.rs:4:9
|
3 | if let Some(v) = vec_2d.last() {
| - help: consider changing this to be a mutable reference: `&mut std::vec::Vec<i32>`
4 | v.push(1);
| ^ `v` is a `&` reference, so the data it refers to cannot be borrowed as mutable
我还尝试了 Some(ref v)
和 Some(ref mut v)
,结果相同。我找不到任何专门描述此错误的文档。什么是正确的方法?
安answer to a similar question推荐一些更像 Some(&mut v)
的东西。然后我得到这些错误:
error[E0308]: mismatched types
--> src/main.rs:3:17
|
3 | if let Some(&mut v) = vec_2d.last() {
| ^^^^^^ types differ in mutability
|
= note: expected type `&std::vec::Vec<_>`
found type `&mut _`
= help: did you mean `mut v: &&std::vec::Vec<_>`?
如果我尝试 Some(&ref mut v)
我得到:
error[E0596]: cannot borrow data in a `&` reference as mutable
--> src/main.rs:3:18
|
3 | if let Some(&ref mut v) = vec_2d.last() {
| ^^^^^^^^^ cannot borrow as mutable
最佳答案
使用 last_mut
获取对最后一个元素的可变引用;无需更改模式。
fn main() {
let mut vec_2d = vec![vec![]];
if let Some(v) = vec_2d.<b>last_mut</b>() {
v.push(1);
}
println!("{:?}", vec_2d);
}
关于vector - 如何在 Rust 中将值推送到 2D Vec?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25151890/