我需要匹配来自方法的self
上的可选值,并基于该匹配,调用self
上的方法,该方法可变地取self
。我试图做一个相当高性能的游戏,所以尽量避免可变性,我不能在这种情况下:方法确实需要可变地访问结构,他们确实需要根据结构属性进行调度。这是一个MVCE:访问Rust中访问属性后调用方法
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
我想我做了我用借检查和平,但显然还没有,我不知道如何解决这个问题,尽管我知道为什么发生这种情况。如果有人在未来解释如何避免这种情况,我将不胜感激。
“访问属性后” - 不只是*访问*,但保留对它的引用。如果'do_a' /'do_b' /'do_c'要改变'self.b',那将违反Rust的内存安全规则,因为不可变的引用已经改变了。 – Shepmaster