我需要匹配来自某个方法的self
上的可选值,并根据该匹配,调用self
上的方法,该方法可变self
。我正在尝试做一个非常高性能的游戏,所以尽管我想免除可变性,我不能在这种情况下:这些方法确实需要可变地访问结构,他们确实需要根据结构属性调度。这是一个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);
}
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
我以为我和借用检查员保持平静,但显然不是:我不知道如何解决这个问题,虽然我知道为什么会这样。如果有人在将来解释如何避免这种情况,我将不胜感激。
答案 0 :(得分:2)
if
let
,而不是使用enum Baz {
A,
B,
C,
}
struct Foo {
bar: Option<Baz>,
}
impl Foo {
pub fn dostuff(&mut self, fizz: i32) {
match self.bar {
Some(Baz::A) => self.do_a(fizz),
Some(Baz::B) => self.do_b(fizz + 2),
Some(Baz::C) => self.do_c(fizz + 1),
None => {},
}
}
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 mut foo = Foo { bar: Some(Baz::B) };
foo.dostuff(3);
}
.. 这是代码......
std::vector < std::vector <int>& > &p_vector2
答案 1 :(得分:1)
如果你关心这些引用,据我所知,Rust的规则禁止你拥有这样的代码。你必须要么:
Copy
或Clone
您的bar
对象并根据您的需要展开。添加一些标志并使代码不具有对该对象的多个引用。例如,添加两个变量,告诉您该怎么做。你匹配你的枚举,设置这些变量,然后匹配这些变量。这比第一项不太有用,但这也是一个解决方案。
更强大功能:
enum Baz {
A,
B,
C,
}
struct Foo {
bar: Option<Baz>,
}
impl Foo {
pub fn dostuff(&mut self, fizz: i32) {
let (method, arg) = match self.bar {
Some(ref b) => {
match b {
&Baz::A => (Self::do_a as fn(&mut Self, i32)>, fizz),
&Baz::B => (Self::do_b as fn(&mut Self, i32)>, fizz + 2),
&Baz::C => (Self::do_c as fn(&mut Self, i32)>, fizz + 1),
}
},
None => return,
};
method(self, arg);
}
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 mut foo = Foo { bar: Some(Baz::A) };
foo.dostuff(3);
}
通过这样做,你会返回一个你想用它调用的方法,所以你只需要调用你需要的东西。我很确定这个解决方案可以在不使用Box
的情况下重写,但只是引用方法,但我不知道如何。