2015-09-17 5 views
6

その要素の条件が真であれば、ベクトルから要素を取得します。条件を満たす場合、どのようにベクトルとポップを覗くことができますか?

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()を使用せずに)借りを終了する方法が表示されません。

+1

無関係なNIT:: 'peek'戻っ'オプション<&String> ''パターンのいくつか(REF e)は '不ますので、' E:&& STRING'これを行う1つの方法は、機能的なスタイルのマップです。 'Some(e)'と書いてください。 – delnan

答えて

7

借用はレキシカルなので、vは機能全体のライフタイムを持ちます。範囲を減らすことができる場合は、last()pop()を使用できます。

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