【发布时间】:2017-02-11 03:22:32
【问题描述】:
我正在与借阅检查器作斗争。我有两段类似的代码,一段按预期工作,另一段没有。
按我预期工作的那个:
mod case1 {
struct Foo {}
struct Bar1 {
x: Foo,
}
impl Bar1 {
fn f<'a>(&'a mut self) -> &'a Foo {
&self.x
}
}
// only for example
fn f1() {
let mut bar = Bar1 { x: Foo {} };
let y = bar.f(); // (1) 'bar' is borrowed by 'y'
let z = bar.f(); // error (as expected) : cannot borrow `bar` as mutable more
// than once at a time [E0499]
}
fn f2() {
let mut bar = Bar1 { x: Foo {} };
bar.f(); // (2) 'bar' is not borrowed after the call
let z = bar.f(); // ok (as expected)
}
}
没有的:
mod case2 {
struct Foo {}
struct Bar2<'b> {
x: &'b Foo,
}
impl<'b> Bar2<'b> {
fn f(&'b mut self) -> &'b Foo {
self.x
}
}
fn f4() {
let foo = Foo {};
let mut bar2 = Bar2 { x: &foo };
bar2.f(); // (3) 'bar2' is borrowed as mutable, but who borrowed it?
let z = bar2.f(); // error: cannot borrow `bar2` as mutable more than once at a time [E0499]
}
}
我希望我可以调用 Bar2::f 两次而不会刺激编译器,就像案例 1 一样。
问题在评论(3):谁借bar2,而没有做作?
这是我的理解:
情况1,
f2调用:lifetime参数'a是接收&Foo值的那个,所以这个lifetime在没有做作的情况下是空的,bar不是借用的在Bar1::f通话之后;在情况2中,
bar2借用foo(作为不可变的),所以Bar2结构中的生命周期参数'b是foo引用生命周期,它在@987654335的末尾结束@ 身体。调用Bar2::f在该生命周期内借用bar2,即到f4的末尾。
但问题仍然存在:谁借了bar2?会不会是Bar2::f?通话后Bar2::f 将如何持有借来的所有权?我在这里错过了什么?
我在 x86_64-pc-windows-msvc 上使用 Rust 1.14.0-nightly (86affcdf6 2016-09-28)。
【问题讨论】:
标签: rust lifetime borrow-checker