首先,让代码说话:不能借用`self.x`为永恒不变的,因为`* self`也借为可变
#[derive(Debug)]
struct Bar;
#[derive(Debug)]
struct Qux {
baz: bool
}
#[derive(Debug)]
struct Foo {
bars: Vec<Bar>,
qux: Qux,
}
impl Foo {
fn get_qux(&mut self) -> &mut Qux {
&mut self.qux
}
fn run(&mut self) {
// 1. Fails:
let mut qux = self.get_qux();
// 2. Works:
// let mut qux = &mut Qux { baz: false };
// 3. Works:
// let mut qux = &mut self.qux;
let qux_mut = &mut qux;
qux_mut.baz = true;
for bar in &self.bars {
println!("{:?}", bar);
}
}
}
fn main() {
println!("Hello, world!");
let mut foo = Foo { bars: vec!(), qux: Qux { baz: false } };
foo.run();
}
此错误:
error[E0502]: cannot borrow `self.bars` as immutable because `*self` is also borrowed as mutable
--> src/main.rs:33:21
|
22 | let mut qux = self.get_qux();
| ---- mutable borrow occurs here
...
33 | for bar in &self.bars {
| ^^^^^^^^^ immutable borrow occurs here
...
36 | }
| - mutable borrow ends here
如果我取消或者2.
或3.
,它为什么编译得很好? 1.
中的被调用函数与2.
或3.
没有任何大的差异。那么为什么1.
无法编译?
虽然有many similar titled questions,但是我不能清楚地将其识别为伪指令(除了错误信息是相同的),可能是因为我对Rust的所有权/借用系统缺乏了解。
谢谢您的详细解答。然而,我想知道,如果必须的话,如何在for循环中使用'qux'? –
@FelixSchlitter已更新。 – Shepmaster
我明白了。但是让我们假设该函数有一些额外的逻辑,例如它需要一个id并从quux的vec中检索到'qux',然后我需要在任何地方添加该逻辑。也许我需要诉诸宏观? ...我知道'HashMap'和'Vec'类型有一个'get_mut'方法,也许有些东西需要从它们的实现中学习。我将不得不再次下潜。 –