这是一个非常简单的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.last_mut() {
v.push(1);
}
println!("{:?}", vec_2d);
}
针对这种特殊情况的(更)更优雅的解决方案是:
fn main() {
let vec_2d = vec![vec![1i32]];
println!("{:?}", vec_2d);
}