Mutable borrow in a loop

后端 未结 1 1161
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-19 06:15

I have the following code:

struct Baz {
    x: usize,
    y: usize,
}

struct Bar {
    baz: Baz,
}

impl Bar {
    fn get_baz_mut(&mut self) -> &         


        
相关标签:
1条回答
  • 2020-12-19 07:00

    It does not work because returning a borrowed value extends the borrow to the end of the function.

    See here for some useful details.

    This works with non-lexical lifetimes with the 1.27 nightly version:

    #![feature(nll)]
    
    struct Baz {
        x: usize,
        y: usize,
    }
    
    // ...
    

    The non-lexical lifetimes RFC explains the actual working of lifetimes:

    Problems arise however when you have a reference that spans multiple statements. In that case, the compiler requires the lifetime to be the innermost expression (which is often a block) that encloses both statements, and that is typically much bigger than is really necessary or desired

    rustc nightly 1.28

    As pointed out by @pnkfelix, the non-lexical lifetimes implementation starting from nightly 1.28 no longer compiles the above code.

    There is however a long-term plan to (re)-enable a more powerful NLL analysis.

    0 讨论(0)
提交回复
热议问题