Who borrowed a variable?

前端 未结 4 1151
庸人自扰
庸人自扰 2021-01-02 02:14

I\'m fighting with the borrow checker. I have two similar pieces of code, one working as I expect, and the other not.

The one that works as I expect:



        
4条回答
  •  粉色の甜心
    2021-01-02 02:40

    I put the body of f4() in a main() and implemented Drop for Bar2 to find out when it is dropped (i.e. goes out of scope):

    impl<'b> Drop for Bar2<'b> {
        fn drop(&mut self) { println!("dropping Bar2!"); }
    }
    

    And the result was:

    error: `bar2` does not live long enough
      --> :24:5
       |
    24 |     bar2.f();
       |     ^^^^ does not live long enough
    25 | }
       | - borrowed value dropped before borrower
       |
       = note: values in a scope are dropped in the opposite order they are created
    

    Something's fishy; let's examine it in detail, with helper scopes:

    fn main() {
        {
            let foo = Foo {}; // foo scope begins
            {
                let mut bar2 = Bar2 { x: &foo }; // bar2 scope begins; bar2 borrows foo
                bar2.f();
            } // bar2 should be dropped here, but it has the same lifetime as foo, which is still live
        } // foo is dropped (its scope ends)
    }
    

    It looks to me that there is a leak here and bar2 is never dropped (and thus Drop cannot be implemented for it). That's why you cannot re-borrow it.

提交回复
热议问题