rust - 错误 : borrowed value is only. .. 引用必须有效

标签 rust

我在编译下面的代码(代码 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


我读到了这个ownership还有这个borrowing

最佳答案

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

这是一个更简单的例子:

{
    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/

相关文章:

rust - 实现嵌套特征

rust - 如何在 Rust 中清除或删除 io::stdin 缓冲区?

enums - 如何找到枚举变体的参数数量?

c - 处理 C 的 Null 终止指针 (ffi)

rust - 派生特征会导致意外的编译器错误,但手动实现有效

rust - future 生成器关闭时出错 : Captured variable cannot escape `FnMut` closure body

rust - `use path::{self}` 是什么意思?

Rust 坚持认为可克隆结构的通用参数也必须实现 Clone

rust - 预期的绑定(bind)生命周期参数,找到具体的生命周期

c - Rust 静态函数 fn 指针,初始化哪个值?