<分区>
我需要从一个方法匹配 self
上的可选值,并根据该匹配调用 self
上的方法,该方法采用 self
可变。我正在尝试做一个非常高性能的游戏,所以尽管我很想放弃可变性,但在这种情况下我做不到:这些方法确实需要可变地访问结构,而且它们确实需要根据结构属性进行分派(dispatch)。这是一个 MVCE:
enum Baz {
A,
B,
C,
}
struct Foo {
bar: Option<Baz>,
}
impl Foo {
pub fn dostuff(&mut self, fizz: i32) {
if let Some(ref b) = self.bar {
match b {
&Baz::A => self.do_a(fizz),
&Baz::B => self.do_b(fizz + 2),
&Baz::C => self.do_c(fizz + 1),
}
}
}
pub fn do_a(&mut self, f: i32) {
println!("A, with fizz {}", f);
}
pub fn do_b(&mut self, f: i32) {
println!("B, with fizz {}", f);
}
pub fn do_c(&mut self, f: i32) {
println!("C, with fizz {}", f);
}
}
fn main() {
let foo = Foo { bar: Some(Baz::A) };
foo.dostuff(3);
}
这里是 the playground .
error[E0502]: cannot borrow `*self` as mutable because `self.bar.0` is also borrowed as immutable
--> src/main.rs:14:28
|
12 | if let Some(ref b) = self.bar {
| ----- immutable borrow occurs here
13 | match b {
14 | &Baz::A => self.do_a(fizz),
| ^^^^ mutable borrow occurs here
...
18 | }
| - immutable borrow ends here
我以为我已经与借用检查器和平相处,但显然不是:我不知道如何解决这个问题,尽管我知道为什么会这样。如果有人解释了将来如何避免这种情况,我将不胜感激。