Rust不能一次多次使用`x`作为可变的

时间:2017-08-10 05:21:28

标签: rust borrow-checker

我有以下代码:

|----------|
|   Tax    |
|----------|
|Name|  %  |
|----|---- |
|    |     |
|    |     | 
|    |     |
|----------|

我收到了一个错误:

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
}

如何在Rust中有效地实现它?到目前为止,我已尝试使用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 BoxRc,但没有运气。

1 个答案:

答案 0 :(得分: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 => {}
}