错误:借用值仅为参考...必须是有效的为

问题描述:

编译下面的代码时,我得到这些错误(代码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

是,这种行为是绝对正常和自然的。

这里有一个简单的例如:

{ 
    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已被破坏。