Non-lexical lifetimes: pushing to an interior Vec obtained from outer Vec.last()

So this example will not compile due the the second statement trying to mutate a vec which came from a last() call. What is the most idiomatic way to do this? I am iterating over something and will conditionally push empty vecs to my outer vec, and in the case that there is an inner vec, I want to push things to the last inner vec. Thanks for any guidance!

let mut vector: Vec<i32> = Vec::new();

if let Some(last_value) = vector.last() {
    vector.push(*last_value + 1);
}
//fails to compile
let mut vec_of_vecs: Vec<Vec<i32>> = vec![];
if let Some(last_value) = vec_of_vecs.last() {
    last_value.push(1);
}

Instead of last(), use last_mut().

let mut vec_of_vecs: Vec<Vec<i32>> = vec![];
if let Some(last_value) = vec_of_vecs.last_mut() {
    last_value.push(1);
}
1 Like

Boom! This works great. Thanks for the quick response!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.