【问题标题】:Error: borrowed value is only... reference must be valid for错误:借来的值只是...引用必须对
【发布时间】:2016-04-02 21:25:29
【问题描述】:

编译下面的代码(代码 1)时出现这些错误

错误:v 寿命不够长 vec.push(&v);

注意:引用必须对以下语句的块后缀有效 0 点 15:64...

注意:...但是借用的值只对块后缀有效 以下是 19:35 的声明 2

(代码 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);

但当我移动vecpv 下方时不会。

(代码 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

【问题讨论】:

    标签: rust


    【解决方案1】:

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

    这是一个更简单的例子:

    {
        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 的未完成引用,该引用已被销毁。

    【讨论】:

      猜你喜欢
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      • 2019-08-15
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 2018-08-01
      相关资源
      最近更新 更多