gpt4 book ai didi

rust - 如果满足条件,如何查看向量并弹出?

转载 作者:行者123 更新时间:2023-11-29 07:47:56 25 4
gpt4 key购买 nike

如果元素的条件为真,我想从向量中检索该元素。

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() {}

playground

这会导致错误:

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())。

最佳答案

借用是词法的,所以 v 有整个函数的生命周期。如果可以缩小范围,可以使用 last()pop()。一种方法是使用函数式 map :

let mut v: Vec<String> = vec!["foo".to_string()];
if v.last().map_or(false, check) {
v.pop()
} else {
None
}

关于rust - 如果满足条件,如何查看向量并弹出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32634634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com