The result of vector.last() is Option<&i32> . A link in this value saves the borrowed vector. We need to get rid of all the links in the vector before we can click on it.
If your vector contains Copy capable values, copy the value from the vector to finish borrowing earlier.
fn main () { let mut vector: Vec<i32> = Vec::new(); match vector.last() { Some(&last_value) => vector.push(last_value + 1), None => (), } }
Here I used the template Some(&last_value) instead of Some(last_value) . This destroys the link and makes it copy. If you try this template with a type that Copy is not capable of, you will get a compiler error:
<anon>:5:14: 5:25 error: cannot move out of borrowed content <anon>:5 Some(&last_value) => vector.push(last_value + "abc"), ^~~~~~~~~~~
If your vector does not contain Copy capable types, you might want to clone the value first:
fn main () { let mut vector: Vec<String> = Vec::new(); match vector.last().map(|v| v.clone()) { Some(last_value) => vector.push(last_value + "abc"), None => (), } }
Or you can convert the value differently so that the .map() call returns a value that is not taken from the vector.
fn main () { let mut vector: Vec<String> = Vec::new();
source share