如果该元素的条件为真,我想从向量中检索元素。
fn draw() -> Option<String> {
let mut v: Vec<String> = vec!["foo".to_string()];
let t: Option<String>;
let o = v.last();
// t and v are actually a fields in a struct
// so their lifetimes will continue outside of draw().
match o {
Some(ref e) => {
if check(e) {
t = v.pop();
t.clone()
} else {
None
}
}
None => None,
}
}
fn check(e: &String) -> bool {
true
}
fn main() {}
这会导致错误:
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
--> src/main.rs:12:21
|
4 | let o = v.last();
| - immutable borrow occurs here
...
12 | t = v.pop();
| ^ mutable borrow occurs here
...
20 | }
| - immutable borrow ends here
我有点理解,但是我没有办法结束借阅(不使用clone()
)。
答案 0 :(得分:8)
借用是词汇,因此v
具有整个功能的生命周期。如果可以缩小范围,可以使用last()
和pop()
。一种方法是使用功能样式的地图:
let mut v: Vec<String> = vec!["foo".to_string()];
if v.last().map_or(false, check) {
v.pop()
} else {
None
}