How can I look into a vector and pop if the condition is met?

I want to get an element from a vector if the condition for this 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() {} 

playground

This results in an error:

 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 

What kind I understand, however, I see no way to end the loan (without using clone() ).

+6
source share
1 answer

The harrows are lexical, so v has a lifetime of the entire function. If you can reduce the scope, you can use last() and pop() . One way to do this is with a functional style card:

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

All Articles