Welcome to unit 4 on lifetimes. In the context of Rust,
when we talk about lifetimes,
we're talking about the length of time that a reference to some value may exist.
The Rust compiler ensures that all references have valid lifetimes.
References only exist while the value they point to has not been moved to another location or been cleaned up.
You can do a lot in Rust without having to think about lifetimes explicitly.
And as long as your code compiles,
you know that all of your references are valid.
However,
the Rust compiler has limits and occasionally needs extra information from us programmers to understand how the lifetime of references relate to each other.
The way we provide the compiler with this information is by using generic lifetime parameter annotations.
The goal of this unit is to give you an understanding of the analysis the compiler performs, so that when you get an error message involving lifetimes,
you'll know how to specify lifetime annotations or restructure your code to fix the problem.
To that end, module 2 is an exploration of concrete lifetimes.
We'll see how the borrow checker part of the compiler prevents problems that occur at runtime in other languages. In module 3, we'll visualize lifetimes of values and references
to help us understand borrow checker errors.
Module 4 will introduce the concept of generic lifetimes.
We'll
look at how Rust analyzes functions with parameters and return types that are references, without knowing what those functions will be called with.
Module 5 will take a quick detour to cover how to specify generic type parameters for when you want to write code once that can be used with many types rather than one concrete type.
We're taking that detour because in module 6, we'll cover how to specify generic lifetime parameters for when you want to write code
once that could be used with multiple lifetimes rather than one concrete lifetime.
The syntax for generic type parameters and generic lifetime parameters is similar.
In module 7,
we'll see how generic lifetime parameters are descriptive,
not prescriptive.
We can't change the lifetime of any reference by specifying lifetime parameters.
The purpose of lifetime parameters is only to describe to the compiler how the lifetimes of references are related.
Finally,
in module 8, we'll get to know the lifetime elision rules.
These rules are how the compiler understands code when we don't specify lifetime parameters, and is why we don't have to annotate every reference.
Let's get started!