【发布时间】:2018-10-11 05:22:28
【问题描述】:
我有以下代码:
struct Baz {
x: usize,
y: usize,
}
struct Bar {
baz: Baz,
}
impl Bar {
fn get_baz_mut(&mut self) -> &mut Baz {
&mut self.baz
}
}
struct Foo {
bar: Bar,
}
impl Foo {
fn foo(&mut self) -> Option<&mut Baz> {
for i in 0..4 {
let baz = self.bar.get_baz_mut();
if baz.x == 0 {
return Some(baz);
}
}
None
}
}
编译失败:
error[E0499]: cannot borrow `self.bar` as mutable more than once at a time
--> src/main.rs:23:23
|
23 | let baz = self.bar.get_baz_mut();
| ^^^^^^^^ mutable borrow starts here in previous iteration of loop
...
29 | }
| - mutable borrow ends here
但是,如果我从 Foo::foo 返回 Some(baz.x)(并将返回类型更改为 Option<usize>),则代码会编译。这让我相信问题不在于循环,即使编译器似乎表明了这一点。更具体地说,我相信本地可变引用 baz 将在循环的下一次迭代中超出范围,导致这不是问题。以上代码的生命周期问题是什么?
以下问题类似:
- Mutable borrow in loop
- Linking the lifetimes of self and a reference in method
- Cannot borrow as mutable more than once at a time in one code - but can in another very similar
但是,它们处理显式声明的生命周期(特别是这些显式生命周期是答案的一部分)。我的代码省略了这些生命周期,因此删除它们是不可行的。
【问题讨论】:
-
我很惊讶我没有找到这个问题的副本,但我通常不擅长在 SO 中搜索问题。可能是因为您的示例不是很地道,可能太简单而无法表达真正的问题。
标签: reference rust mutable lifetime