2016-04-02 64 views
0

編譯下面的代碼時,我得到這些錯誤(代碼1)錯誤:借用值僅爲參考...必須是有效的爲

error: v does not live long enough vec.push(&v);

note: reference must be valid for the block suffix following statement 0 at 15:64...

note: ...but borrowed value is only valid for the block suffix following statement 2 at 19:35

(代碼1)

fn main() { 

    let mut vec: Vec<&Inf> = Vec::<&Inf>::new();//<-- It appears the error 

    let p: Foo1 = Foo1::created(); 
    let v: Foo2 = Foo2::created(); 

    vec.push(&v); 
    vec.push(&p); 

但不是當我移動vec,低於pv

(代碼2)

fn main() { 

    let p: Foo1 = Foo1::created(); 
    let v: Foo2 = Foo2::created(); 

    //It does not appear the error described above 
    let mut vec: Vec<&Inf> = Vec::<&Inf>::new(); //<-- It does not appear the error 
    vec.push(&v); 
    vec.push(&p); 

..// 

(此行爲可能是正常的,如果是別人我可以解釋我的。)

這是我創建的,所以你可以看到錯誤的類似病例


錯誤play.rust

沒有錯誤play.rust


我讀到這個ownershipborrowing

回答

5

是,這種行爲是絕對正常和自然的。

這裏有一個簡單的例如:

{ 
    let x = 1; 
    let mut v = Vec::new(); 

    v.push(&x); 
} 

此代碼編譯,但這並不:

{ 
    let mut v = Vec::new(); 
    let x = 1; 

    v.push(&x); 
} 

這是因爲變量破壞秩序是他們的建築順序相反。在頂部例如,它是這樣的:

x created 
v created 
v[0] = &x 
v destroyed 
x destroyed 

但在底部有一個,我們有這樣的:

v created 
x created 
v[0] = &x 
x destroyed // x is destroyed, but v still holds a reference to x! 
v destroyed 

也就是說,在底部的例子有一個時刻(雖然接近無形的),當有一個突出的參考x已被破壞。

相關問題