代码之家  ›  专栏  ›  技术社区  ›  soupybionics

当返回对范围外的值的可变引用的不可变引用时,为什么在范围结束时删除可变引用?

  •  10
  • soupybionics  · 技术社区  · 6 年前
    fn main() {
        // block1: fails
        {
            let mut m = 10;
    
            let n = {
                let b = &&mut m;
                &**b // just returning b fails
            };
    
            println!("{:?}", n);
        }
    
        // block2: passes
        {
            let mut m = 10;
    
            let n = {
                let b = &&m;
                &**b // just returning b fails here too
            };
    
            println!("{:?}", n);
        }
    }
    

    BLUT1 失败,错误为:

    error[E0597]: borrowed value does not live long enough
      --> src/main.rs:7:22
       |
    7  |             let b = &&mut m;
       |                      ^^^^^^ temporary value does not live long enough
    8  |             &**b // just returning b fails
    9  |         };
       |         - temporary value dropped here while still borrowed
    ...
    12 |     }
       |     - temporary value needs to live until here
    

    假设内部不可变引用扩展到 方块2 范围,而在 BLUT1 ,即使有外部引用,也始终删除内部可变引用?

    1 回复  |  直到 6 年前
        1
  •  6
  •   Shepmaster Lukas Kalbertodt    6 年前

    Copy S

    n m

    struct S { m: i32 }
    let mut m = 10;
    
    let n = {
        let s = S { m };
        let b = &s;
        &(*b).m
    }; // s is dropped
    
    println!("{:?}", n);
    

    s

    let mut m = 10;
    
    let n = {
        let m2 = m;
        let mut a = &m2;
        let b = &a;
        &**b
    };
    
    println!("{:?}", n);