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:
Ah... you basically self-borrowed yourself.
The issue hinges on the fact that you have the same lifetime ('b
) used for both the lifetime of Foo
and the lifetime of Bar
. The compiler then dutifully unifies those lifetimes, and you end up in a strange situation where suddenly the lifetime of the borrow which should have ended at the end of the statement instead ends after the value should have gone out of scope.
As a rule of thumb: always use a fresh lifetime for self
. Anything else is weird.
It's interesting to note that this pattern can actually be useful (though more likely with an immutable borrow): it allows anchoring a value to a stack frame, preventing any move after the call to the function, which is (sometimes) useful to represent a borrow that is not well-modeled by Rust (like passing a pointer to the value to FFI).