Rust lifetimes versus Go garbage-collected lifetimes
understanding of how Rust tracks reference validity.
a lifetime is a compile-time region a reference is valid for; annotations like 'a relate input and output reference durations; Go instead uses garbage collection and escape analysis.
WHAT THIS TESTS It verifies you understand lifetimes as a compile-time mechanism that prevents dangling references, and that you can contrast it with Go's runtime garbage collection.
A GOOD ANSWER COVERS A lifetime is the span of code during which a reference is valid. The borrow checker uses lifetimes to guarantee no reference outlives the data it points to. Generic lifetime parameters, written like 'a, do not change behavior or add cost; they let you express relationships between the validity of input and output references so the compiler can prove safety. They are erased before code generation. In Go there are no lifetimes in the type system; object lifetime is determined dynamically by the garbage collector, while the compiler's escape analysis decides whether a value lives on the stack or heap.
A SIMPLE SIGNATURE fn longest<'a>(x: &'a str, y: &'a str) -> &'a str. This says the returned reference is valid for at least the shorter of the two input lifetimes, so callers cannot use the result after either input has been dropped.
COMMON WRONG ANSWERS Saying lifetimes are a runtime feature or that they free memory. Confusing lifetimes with the actual scope of a variable. Claiming Go uses lifetime annotations.
LIKELY FOLLOW-UPS What is lifetime elision and when can you omit annotations? Why can the longest function not return a reference to a local? How does escape analysis in Go differ from ownership in Rust?
ONE CONCRETE EXAMPLE Without the lifetime, fn longest(x: &str, y: &str) -> &str is ambiguous: the compiler cannot tell whether the output borrows from x, from y, or from something else, so it rejects the code. Annotating both inputs and the output with 'a tells the compiler the result lives no longer than either argument. Then code that stores the result and uses it after one argument goes out of scope is rejected at compile time. In Go, the same idea would just return a string and let the garbage collector keep the backing data alive as long as any reference exists, deferring the safety question to runtime memory management.
Read the original → doc.rust-lang.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.