我正在與借閱檢查員爭鬥。我有兩個類似的代碼片斷,其中一個按我期望的工作,另一個不工作。誰借了一個變量?
的一個,因爲我期待的作品:
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
電話:壽命參數'a
是接收&Foo
值的一個,所以這一輩子是空的時,有沒有做作,和bar
是撥打Bar1::f
後不會借用;在情況2中,
bar2
借用foo
(爲不可改變),所以壽命參數'b
在Bar2
結構是foo
壽命基準時間,其在f4
本體的端部終止。調用Bar2::f
借用bar2
該生存期,即到f4
的末尾。
但問題仍然是:誰借了bar2
?難道是Bar2::f
?通話結束後Bar2::f
如何保留借來的所有權?我在這裏錯過了什麼?
我在x86_64-pc-windows-msvc上使用Rust 1.14.0-nightly(86affcdf6 2016-09-28)。
接受因爲這個有價值的經驗法則。謝謝。 – jferard