Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pushing something into a vector depending on its last element

I would like to get the last element of a vector and use it to determine the next element to push in. Here's an example how it doesn't work, but it shows what I'm trying to achieve:

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

if let Some(last_value) = vector.last() {
    vector.push(*last_value + 1);
}

I can't use push while the vector is also borrowed immutably:

error[E0502]: cannot borrow `vector` as mutable because it is also borrowed as immutable
 --> src/main.rs:5:9
  |
4 |     if let Some(last_value) = vector.last() {
  |                               ------ immutable borrow occurs here
5 |         vector.push(*last_value + 1);
  |         ^^^^^^ mutable borrow occurs here
6 |     }
  |     - immutable borrow ends here

What would be a good way to do this?

like image 631
Stefan Pfeifer Avatar asked Oct 27 '15 03:10

Stefan Pfeifer


1 Answers

After Non-Lexical Lifetimes

Your original code works as-is in Rust 2018, which enables non-lexical-lifetimes:

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

    if let Some(last_value) = vector.last() {
        vector.push(*last_value + 1);
    }
}

The borrow checker has been improved to realize that the reference in last_value does not overlap with the mutable borrow of vector needed to push a new value in.

See Returning a reference from a HashMap or Vec causes a borrow to last beyond the scope it's in? for a similar case that the borrow checker is not yet smart enough to deal with (as of Rust 1.32).

Before Non-Lexical Lifetimes

The result of vector.last() is an Option<&i32>. The reference in that value keeps the vector borrowed. We need to get rid of all references into the vector before we can push to it.

If your vector contains Copyable values, copy the value out of the vector to end the borrow sooner.

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

    if let Some(&last_value) = vector.last() {
        vector.push(last_value + 1);
    }
}

Here, I've used the pattern Some(&last_value) instead of Some(last_value). This destructures the reference and forces a copy. If you try this pattern with a type that isn't Copyable, you'll get a compiler error:

error[E0507]: cannot move out of borrowed content
 --> src/main.rs:4:17
  |
4 |     if let Some(&last_value) = vector.last() {
  |                 ^----------
  |                 ||
  |                 |hint: to prevent move, use `ref last_value` or `ref mut last_value`
  |                 cannot move out of borrowed content

If your vector does not contain Copyable types, you might want to clone the value first:

fn main() {
    let mut vector: Vec<String> = Vec::new();

    if let Some(last_value) = vector.last().cloned() {
        vector.push(last_value + "abc");
    }
}

Or you can transform the value in another way such that the .map() call returns a value that doesn't borrow from the vector.

fn main() {
    let mut vector: Vec<String> = Vec::new();

    if let Some(last_value) = vector.last().map(|v| v.len().to_string()) {
        vector.push(last_value);
    }
}
like image 128
Francis Gagné Avatar answered Sep 19 '22 10:09

Francis Gagné