如果满足条件,如何查看向量并弹出? [英] How can I peek into a vector and pop if a condition is met?
本文介绍了如果满足条件,如何查看向量并弹出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果某个元素的条件为真,我想从向量中检索该元素.
I want to retrieve an element from a vector if a condition on that element is true.
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()
).
Which I sort of understand, however I don't see a way to end the borrow (without using clone()
).
推荐答案
借用是词法的,所以 v
具有整个函数的生命周期.如果可以缩小范围,可以使用last()
和pop()
.一种方法是使用函数式地图:
Borrows are lexical, so v
has the life-time of the whole function. If one can reduce the scope, one can use last()
and pop()
. One way to do this is a functional-style map:
let mut v: Vec<String> = vec!["foo".to_string()];
if v.last().map_or(false, check) {
v.pop()
} else {
None
}
这篇关于如果满足条件,如何查看向量并弹出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文