Rust 一次不能多次借用 `x` 作为可变的
Rust cannot borrow `x` as mutable more than once at a time
我有以下代码:
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
如何在 Rust 中有效地实现它?到目前为止,我已经尝试使用 Box
、Rc
和 RefCell
,但没有成功。
现在,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 => {}
}
我有以下代码:
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
如何在 Rust 中有效地实现它?到目前为止,我已经尝试使用 Box
、Rc
和 RefCell
,但没有成功。
现在,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 => {}
}