Confusion around borrow checker analysis of loops
I've run into a case where borrow checker seems to think that returning from a function mid loop can result in a mutable borrow being held over into another iteration of a loop.
I've put together a simplified example. The curious part is in the lastfn, the rest is just fluff to justify the signature.
How I mentally check borrows in loops is to figure out what borrows survive over a loop iteration after the drops at the end of the scope occur and make sure that no incompatible borrows occur. In this case we can see that the candidate reference to be returned gets dropped before another iteration can occur and that there is no sub-borrow of self crossing iterations.
The compiler on the other hand seems to be working backwards from the lifetime of the return type and using that to assert that any borrow created fromself that could be returned should be treated as though it definitely is living as long as a returned type and therefore self is permanently borrowed each iteration.
Is that whats happening? Does anyone have a workarounds to suggest? All I have are the ugly options of Arcs or Clones.
Edit: it looks like the consensus is that this is behaviour as intended, unfortunately. Is there any chance of creating UB if the loop returns a pointer which is then, after the loop, converted to a reference with a lifetime bound by self, like so?
Posted May 20, 2020, 10:33 AM UTC · edited
This sadly is a limitations of the current borrow checker. I can't explain this very well myself, but there is a great talk by Niko Matsakis, which explains this problem and how it may be solved in the somewhat near future: https://youtu.be/_agDeiWek8w?t=1501
Thanks, I'll have a look. Clearly I need to update my understanding of how the current borrowing checks are performed.
Edit: Yep that was exactly the same problem.