简体   繁体   English

如何将值推送到Rust中的2D Vec?

[英]How do I push a value into a 2D Vec in Rust?

Here is a really simple attempt at a 2D Vec . 这是2D Vec一个非常简单的尝试。 I'm trying to add an element to the last entry in the top-level Vec : 我正在尝试在顶级Vec的最后一个条目中添加一个元素:

fn main() {
    let mut vec_2d = vec![vec![]];
    if let Some(v) = vec_2d.last() {
        v.push(1);
    }
    println!("{:?}", vec_2d);
}

I get this error: 我收到此错误:

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

I've also tried Some(ref v) and Some(ref mut v) with the same results. 我也试过Some(ref v)Some(ref mut v) ,结果相同。 I can't find any documentation that describes this error specifically. 我找不到任何具体描述此错误的文档。 What is the right approach here? 这里的正确方法是什么?

An answer to a similar question recommends something more like Some(&mut v) . 对类似问题的回答建议更像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<_>`?

If I try Some(&ref mut v) I get: 如果我尝试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

Grab a mutable reference to the last element with last_mut ; 使用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);
}

A (much) more elegant solution for this particular case would be: 针对这种特殊情况的(更)更优雅的解决方案是:

fn main() {
    let vec_2d = vec![vec![1i32]];

    println!("{:?}", vec_2d);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM