2016-04-13 7 views
0

私はpat_vecstr_vecは2回の反復子です。このコードを持っている:これは動作しません回避方法RustのHashMapの借用確認ですか?

let mut pat_mapping: HashMap<char, &str> = HashMap::new(); 

for combi in pat_vec.zip(str_vec) { 
    let (c, word) = combi; 

    match pat_mapping.get(&c) { 
     Some(phrase) => { 
      if phrase.to_string() != word.to_string() { 
       return false; 
      } 
     } 

     None => { 
      pat_mapping.insert(c, word); 
     } 
    } 
} 

、およびコンパイラがと文句を言い:

cannot borrow `pat_mapping` as mutable because it is also borrowed as immutable [E0502] 

が、私はそれがpat_mapping.get(&c)は不変として&selfを借り可能性があるためと理解をメソッドは同じスコープに入りますが、&selfを変更可能として借用する必要があります。

私の周りの仕事があります

match word_mapping.get(&c) { 
    Some(phrase) => { 
     if phrase.to_string() != word.to_string() { 
      return false; 
     } 
    } 
    None => { 

     pat_trigger = true; 
    } 

}; 

if pat_trigger { 
    pat_mapping.insert(c, word); 
} 

をしかし、ブール値のフラグを導入することは冗長です。借り入れチェックを回避して、同じコードブロックにマッチして挿入する方法はありますか?

答えて

1

あなたはentryを使用したい:

match pat_mapping.entry(c) { 
    Occupied(phrase) => { 
     if phrase.get().to_string() != word.to_string() { 
      return false; 
     } 
    }, 
    Vacant(vacant) => { 
     vacant.insert(word); 
    } 
} 

また、一度だけのキーを検索するという利点があります。

関連する問題