Who borrowed a variable?

前端 未结 4 1154
庸人自扰
庸人自扰 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条回答
  •  Happy的楠姐
    2021-01-02 02:53

    In case #2, you have this:

    impl<'b> Bar2<'b> {
        fn f(&'b mut self) -> &'b Foo {
            self.x
        }
    }
    

    To highlight: &'b mut self and &'b Foo have the same lifetime specified.

    This is saying that the reference to self and the returned reference to an instance of a Foo both have the same lifetime. Looking at the call site, you have this:

    let foo = Foo {};
    let mut bar2 = Bar2 { x: &foo };
    

    So the compiler is inferring that both foo and bar2 have the same lifetime. The lifetime of foo is the scope of the f4 function, and so the mutable reference to bar2 shares this.

    One way to fix this, is to remove the explicit lifetime on the self reference:

    fn f(&mut self) -> &'b Foo
    

    This compiles and the compiler correctly understands that the reference to bar2 and the reference to foo have different lifetimes.

    Playground: https://play.rust-lang.org/?gist=caf262dd628cf14cc2884a3af842276a&version=stable&backtrace=0

    TLDR: Yes, having the same lifetime specifier on the self reference and the returned reference means that the entire scope of f4 holds a mutable borrow of bar2.

提交回复
热议问题