`*(&'a mut self)`方法中的生命周期参数是否会混淆BorrowChecker?

Byr*_*ron 2 rust

如以下示例只要不编译'a中使用&'a mut self:

struct Foo<'a> {
    a: &'a u64,
}

impl<'a> Foo<'a> {
    fn mutate_internal(&'a mut self) {}

    fn mutate(&'a mut self) {
        self.mutate_internal();
        self.mutate_internal(); // <- This call fails the borrow-check
    }
}
Run Code Online (Sandbox Code Playgroud)

编译器使我惊讶于以下错误消息:

tests/lang.rs:1116:13: 1116:17 error: cannot borrow `*self` as mutable more than once at a time
tests/lang.rs:1116             self.mutate_internal();
                               ^~~~
tests/lang.rs:1115:13: 1115:17 note: previous borrow of `*self` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `*self` until the borrow ends
tests/lang.rs:1115             self.mutate_internal();
                               ^~~~
tests/lang.rs:1117:10: 1117:10 note: previous borrow ends here
tests/lang.rs:1114         fn mutate(&'a mut self) {
tests/lang.rs:1115             self.mutate_internal();
tests/lang.rs:1116             self.mutate_internal();
tests/lang.rs:1117         }
                           ^
Run Code Online (Sandbox Code Playgroud)

你能解释一下为什么吗?请注意,如果&'a mut self成为问题就会消失&mut self.

? rustc --version
rustc 1.0.0-nightly (e2fa53e59 2015-03-20) (built 2015-03-20)
Run Code Online (Sandbox Code Playgroud)

Pao*_*lla 8

如果你删除'a命名生命周期mutate_internal,你得到的是一个新的(匿名)生命周期参数,而不是'a.即你得到的东西相当于:

fn mutate_internal<'b>(&'b mut self) {}
Run Code Online (Sandbox Code Playgroud)

这意味着自己被借用直到mutate_internal完成,但不再是这样.这就是第二次mutate_internal编译的原因.

相比之下,fn mutate_internal(&'a mut self) {}你告诉编译器自己将被借用'a(只是整个生命周期Foo).这就是为什么第二个mutate_internal不能被调用的原因