我在编译下面的代码(代码 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
移动到 p
和 v
下方时则不会。
(代码 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
最佳答案
是的,这种行为是绝对正常和自然的。
这是一个更简单的例子:
{
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
的未完成引用。
关于rust - 错误 : borrowed value is only. .. 引用必须有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36378897/