Fighting the borrow checker, in a loop


#22

<'b:'a>

I am really confused! So 'a >= 'b means that 'b contains 'a?

{
    let a = scope1;
    {
        let b = scope2;
    }
}

Do we say scope1 contains scope2? (I would)

But then I would say scope1 >= scope2.


#23

Oops, sorry, I meant to say that so 'b can be contained within it :sweat_smile:


#24

This gets a bit subtle :slight_smile:.

In the elision case (or when you don’t express the outlives relationship explicitly), the compiler knows you can’t take advantage of 'b: 'a inside the body of the method - it’s only at the callsite that it makes the lifetimes work out.

In the explicit case you have above, it’s like a “hard requirement”, if you will - you could now code the body of that method knowing that 'b: 'a (eg stash something away with 'b lifetime into an 'a, knowing that b outlives a). The compiler can no longer play games with the lifetimes.


#25

I see, since the function with different lifetime param actually shares code. So the compiler doesn’t realize 'b outlives 'a when compiles the function, until the function is called. Is that the right explain?
So this makes ellision semantics slight different than just syntax sugar ?


#26

Elision should be no different than writing the lifetimes explicitly assuming you write out the same lifetimes and their bounds as elision rules. In other words, elision is purely about ergonomics, not unlocking some additional capabilities.

There are basically two places where lifetimes come into play in the examples here: declaration and use/callsite. The compiler checks them separately - a function declaration and body are checked to make sure they’re valid on their own, without any particular caller. At the use/callsite, the compiler checks the lifetimes just against the signature of the callee - it ensures the caller abides by the lifetime requirements of the callee. And so there are multiple opportunities to get something wrong here, independent of each other :slight_smile:.

NLL mostly, if not entirely, addresses the latter part: improving the uses/callsites, such as by observing that a returned reference is dropped immediately or otherwise dies between loop iterations, as in this thread’s subject.