How to push an element to the last vector in a vector of vectors?

Viewed 367

I am trying to access the last vector in a vector of vectors (Vec<Vec<u32>>) and push a value to it, but I continue to come across errors. A simplified version of what I am trying to do is:

let mut pc: Vec<Vec<u32>> = vec![];

pc.push(vec![1]);

pc.last().unwrap().push(2);

The error I get is:

error[E0596]: cannot borrow data in a `&` reference as mutable                                                                  
   |                                                                                                                            
   |         pc.last().unwrap().push(2);                                                                                        
   |         ^^^^^^^^^^^^^^^^^^ cannot borrow as mutable

I have tried dereferencing the result of unwrap(): (*(pc.last().unwrap())).push(2); but the error persists.

The expected behavior is a nested vector resembling: [[1, 2]].

1 Answers

Instead of last, use last_mut():

fn main(){
    let mut pc:Vec<Vec<i32>> = vec![];
    pc.push(vec![1]);
    pc.last_mut().unwrap().push(2);
    println!("{:?}", pc);
}

Prints: [[1, 2]]

Related