8

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Stefan Pfeifer
  • 593
  • 6
  • 16

1 Answers1

10

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);
    }
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Francis Gagné
  • 60,274
  • 7
  • 180
  • 155
  • Can you explain your first example in comparison with the OP's code? How exactly is it different and where does Copy come into play here? – Jimmy Oct 27 '15 at 05:46
  • 1
    @JimmyCuadra In the OP's code `last_value()` gets matched against `last_value`. Since `last_value()` returns a reference, `last_value` becomes a reference too. However, Francis changed the pattern to `&last_value`, so the reference matches the `&`, and the value itself matches `last_value` and therefore is copied by value. This is called destructuring. – Malcolm Oct 27 '15 at 08:33