【发布时间】:2018-01-18 20:30:26
【问题描述】:
我有以下代码:
enum T {
A(bool),
B(u8),
}
fn main() {
let mut a = vec![T::A(true), T::B(42)];
match a[0] {
T::A(value) => println!("A: {}", value),
T::B(ref mut b) => {
match a[1] {
T::A(value) => println!("One more A: {}", value),
T::B(ref mut value) => *value += 1,
}
*b += 1
}
}
}
编译器抱怨:
error[E0499]: cannot borrow `a` as mutable more than once at a time
--> src/main.rs:11:19
|
8 | match a[0] {
| - first mutable borrow occurs here
...
11 | match a[1] {
| ^ second mutable borrow occurs here
...
17 | }
| - first borrow ends here
我知道问题是因为我有两个对 a 的可变引用,但我找不到解决方案。
【问题讨论】:
-
不幸的是,使用 split_at_mut() 方法,这里建议 stackoverflow.com/questions/30073684/… 没有帮助。我将这一行:
match a[1] {更改为:let (left, right) = a.split_at_mut(1); match right[0] { -
你必须事先做:play.rust-lang.org/…
-
在我的代码中,我确定了在本场比赛之前的第二场比赛中使用的索引。如何做到这一点?
-
将原始数组分成3部分:
a[x]之前,a[x],a[x]之后。第一场比赛将匹配a[x],然后第二场比赛可以使用其他两个部分。
标签: rust pattern-matching borrow-checker