Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

types

vector

rust

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);
}

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. 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). 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:

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
like image 210
benekastah Avatar asked Aug 06 '14 03:08

benekastah


People also ask

How do you make a 2D vector in Rust?

2D vectors don't exist in Rust. You're working with 1D vector that contains more of 1D vectors, so all regular vec operations work, you just need to consider which of them to modify. . collect() makes a new container, in this case a Vec , from an iterator.

How do you initialize a VEC in Rust?

In Rust, there are several ways to initialize a vector. In order to initialize a vector via the new() method call, we use the double colon operator: let mut vec = Vec::new(); This call constructs a new, empty Vec<T> .


1 Answers

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);
}
like image 109
Ry- Avatar answered Oct 03 '22 09:10

Ry-