Dear #RustLang people: How would you explain lifetimes to someone that is new to #rust and #programming? Is there any material aimed to teach this in simple ways?

Edit: Outside of the Rust book. This is not for me, I am teaching Rust for others and looking for alternative ways of explaining.

Validating References with Lifetimes - The Rust Programming Language

@hoodie the first thing that caught me on that page: they explain it after generics. Interesting.
@deavid lifetimes are generics. other languages have a concept of "linear types". The mechanisms are basically the same
Understanding lifetimes in Rust - LogRocket Blog

In this guide, we'll go over the basics of lifetimes and annotations and demonstrate how to work with them. We'll also look at some common scenarios you might run into and walk through how to solve them with lifetimes.

LogRocket Blog

@deavid I think that the best way to understand borrowing and lifetimes is in terms of stack allocation.

Basically, every function allocates memory for its variables on the stack; that memory is freed once the function exits. So other functions can use that memory by reference so long as they're callees of that first function.

If you want to store something on the heap, the *reference* to that thing is stored as a smart pointer on the stack (Box, etc) that deallocates the heap memory when it goes out of scope.

And, you can explicitly give your callee the responsibility of freeing some referenced memory by passing them the associated variable as an owned value.

@deavid Now, this doesn't really satisfy your "new to programming" constraint unless you first explain how call stacks work, but once you've done that then I think describing Rust memory management in terms of stack allocation provides the simplest mental model.
@deavid I think, practically speaking, lifetimes are stack frames. The annotations allow the compiler to determine whether (and enforce that) a variable is below all its reference-holders in the stack, and therefore will not be wiped out before those reference holders
@deavid malloc() and free(). Kidding.

@deavid Maybe this also helps?

Lifetime annotations: why doesn't Rust? - by @mtomassoli

https://github.com/mtomassoli/lifetimes

GitHub - mtomassoli/lifetimes: A question about lifetimes.

A question about lifetimes. Contribute to mtomassoli/lifetimes development by creating an account on GitHub.

GitHub