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 Copy
able 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 Copy
able, 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 Copy
able 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);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…