2017-08-10 37 views
1

我有以下代碼:鏽不能在同一時間借'x`作爲可變不止一次

pub type Blockchain<T> = Vec<Block<T>>; 

pub fn blockchain() -> Blockchain<String> { 
    let size = 10; 
    let mut chain: Blockchain<String> = Vec::with_capacity(size); 
    chain.push(Block::genesis()); 
    for i in 0..(size-1) { 
     match chain.last_mut() { 
      Some(tip) => chain.push(tip.next_block(String::from("yooooo"))), 
      None  => {} 
     } 
    } 
    chain 
} 

我得到一個錯誤:

error[E0499]: cannot borrow `chain` as mutable more than once at a time 
    --> src/blockchain/mod.rs:33:26 
    | 
32 |   match chain.last_mut() { 
    |    ----- first mutable borrow occurs here 
33 |    Some(tip) => chain.push(tip.next_block(String::from("yooooo"))), 
    |       ^^^^^ second mutable borrow occurs here 
34 |    None  => {} 
35 |   } 
    |   - first borrow ends here 

我怎樣纔能有效地實現這個在鏽?到目前爲止,我已嘗試使用Box,RcRefCell,但沒有運氣。

回答

4

現在,Rust中的藉詞是詞彙。錯誤消息顯示借用chain開始於chain.last_mut()並結束於匹配塊的末尾。雖然可以推斷chain的借款在chain.push(...)之前結束,但Rust還不支持它。

解決此類問題的一般原則是重新組織代碼以儘早結束借用。你的情況可能是這樣

let maybe_next_block = chain.last_mut().map(|tip| tip.next_block("some".into())); 
// borrow of `chain` ended 
match maybe_next_block { 
    Some(block) => chain.push(block), 
    None => {} 
} 
+0

注意鏽病將支持這一聲正常:https://github.com/rust-lang/rfcs/pull/2094 – Boiethios

+2

@Boiethios「很快」是一個巨大的* *簡化事實。 RFC甚至還沒有被接受! **如果**被接受,那麼所有參數和細節都需要進行排序,它需要完全實施,迴歸測試,然後搭乘發佈列車。總之,如果它在2017年登陸,我會感到驚訝。 – Shepmaster

+1

當你有一個「匹配」時,如果你只關心一隻手臂,使用'if let'。 – Shepmaster

相關問題