<分区>
这是基于我之前的 question .
我的代码因借用检查器错误而失败,我尽可能地减少了它。这是结果:
struct MyStruct<'a> {
s: &'a str,
}
impl<'a> MyStruct<'a> {
fn foo(&'a mut self) {}
}
fn main() {
let mut m = MyStruct { s: "aaa" };
m.foo();
m.foo();
}
它失败了:
error[E0499]: cannot borrow `m` as mutable more than once at a time
--> src/main-x.rs:13:5
|
12 | m.foo();
| - first mutable borrow occurs here
13 | m.foo();
| ^
| |
| second mutable borrow occurs here
| first borrow later used here
代码减少了很多,以至于它没有做任何有用的事情,并且可以通过例如从 foo
函数中删除 'a
生命周期来修复。但我想了解为什么代码不正常。
我的理解是 MyStruct
包含对某个生命周期 'a
的 str
的引用,并且可以调用 foo
self
指向同一生命周期的 MyStruct
。我不明白为什么 m
在第一次调用 foo
后被认为是可变借用的。