问题描述
这是对 2D Vec
的一个非常简单的尝试.我正在尝试向顶级 Vec
中的最后一个条目添加一个元素:
Here is a really simple attempt at a 2D Vec
. I'm trying to add an element to the last entry in the top-level 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)
得到相同的结果.我找不到任何专门描述此错误的文档.这里的正确方法是什么?
I've also tried Some(ref v)
and Some(ref mut v)
with the same results. I can't find any documentation that describes this error specifically. What is the right approach here?
对类似问题的回答推荐了更像 Some(&mut v)
.然后我收到这些错误:
An answer to a similar question recommends something more like Some(&mut v)
. Then I get these errors:
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)
我得到:
If I try Some(&ref mut v)
I get:
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
;无需更改模式.
Grab a mutable reference to the last element with last_mut
; no need to change patterns.
fn main() {
let mut vec_2d = vec![vec![]];
if let Some(v) = vec_2d.last_mut() {
v.push(1);
}
println!("{:?}", vec_2d);
}
这篇关于如何将值推送到 Rust 中的 2D Vec 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!