`*(&'a mut self)` 方法中的生命周期参数是否会混淆 BorrowChecker?
Do lifetime parameters in `*(&'a mut self)` methods confuse the BorrowChecker?
下面的例子只要在&'a mut self
中使用'a
就不会编译:
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
}
}
编译器出现以下错误消息让我感到惊讶:
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 }
^
你能解释一下为什么吗?请注意,如果 &'a mut self
变成 &mut self
,问题就会消失。
元
✗ rustc --version
rustc 1.0.0-nightly (e2fa53e59 2015-03-20) (built 2015-03-20)
如果您在 mutate_internal
中删除 'a
命名生命周期,您得到的是一个新的(匿名)生命周期参数,而不是 'a
。 IE。你得到的东西相当于:
fn mutate_internal<'b>(&'b mut self) {}
这意味着 self 被借用直到 mutate_internal
完成,但不会超过此时间。这就是为什么第二次调用 mutate_internal
编译。
相比之下,对于 fn mutate_internal(&'a mut self) {}
,您是在告诉编译器只要 'a
(即 Foo
的整个生命周期)就会借用 self。所以第二个mutate_internal
不能叫
下面的例子只要在&'a mut self
中使用'a
就不会编译:
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
}
}
编译器出现以下错误消息让我感到惊讶:
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 }
^
你能解释一下为什么吗?请注意,如果 &'a mut self
变成 &mut self
,问题就会消失。
元
✗ rustc --version
rustc 1.0.0-nightly (e2fa53e59 2015-03-20) (built 2015-03-20)
如果您在 mutate_internal
中删除 'a
命名生命周期,您得到的是一个新的(匿名)生命周期参数,而不是 'a
。 IE。你得到的东西相当于:
fn mutate_internal<'b>(&'b mut self) {}
这意味着 self 被借用直到 mutate_internal
完成,但不会超过此时间。这就是为什么第二次调用 mutate_internal
编译。
相比之下,对于 fn mutate_internal(&'a mut self) {}
,您是在告诉编译器只要 'a
(即 Foo
的整个生命周期)就会借用 self。所以第二个mutate_internal
不能叫