Hi there,
Is it correct to say that the concept of lifetime is useful at compile time as it informs the compiler of the consistency of references while at runtime it is the borrow checker that takes care of this consistency?
If this is the case, the concept of lifetime is really difficult for me to understand in terms of usefulness since the real work is done by the borrow checker...
May be easy, not for me.
Thx.
The borrow checker is the part of the compiler that verifies borrows are valid (consistent) at compile time. There is no borrow checker at runtime, unless you are talking about the runtime checks in a type like RefCell<T>
or other wrapper types.
The example of the longest
function here shows why the borrow checker sometimes needs help from the programmer to resolve ambiguous lifetimes.
https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#generic-lifetimes-in-functions
To add, the real work is definitely not done by the borrow checker. It's only a proofreader. It can tell you when the facts put forth in your program are incorrect, it can't formulate a correction itself.
Said another way, your responsibility as a programmer is to write correct code. The borrow checker's responsibility is to ensure you didn't make any mistakes [1].
With respect to references, anyway. Correctness proper is the absence of logic errors. The borrow checker will not help you out there. âŠī¸
Ok, thanks everyone.... I have to think about it some more.... at the moment it's not clear to me how an <'a> can change things so profoundly without modifying anything in the life cycle of the individual elements but I'll study some examples.
One thing to be aware of while getting the hang of this is that Rust lifetimes -- those '_
things -- are not the same as the liveness scope variables/values. Rust lifetimes are, generally speaking, the duration of a borrow. "Lifetime" is an unfortunately overloaded term.
You cannot borrow a variable for longer than its liveness scope, so they are related, but they are not the same thing.