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

后端 未结 1 1945
死守一世寂寞
死守一世寂寞 2021-01-12 05:53

I want to retrieve an element from a vector if a condition on that element is true.

fn draw() -> Option {
    let mut v: Vec =         


        
相关标签:
1条回答
  • 2021-01-12 06:35

    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
    }
    
    0 讨论(0)
提交回复
热议问题