-
Book Overview & Buying
-
Table Of Contents
Rust for C++ Developers
By :
To be able to validate our whole program, it's crucial for the compiler to always understand whether the owner of a borrowed piece of data remains alive and in scope. In some cases, this analysis is beyond the compiler's ability, and it leans on us to help it. This is where lifetime annotations come into play.
Every reference in Rust has a lifetime. Tracking these lifetimes is one of the most important jobs of the borrow checker. We've already seen how it works to prevent references from data that has been freed by going out of scope.
Most of the time, we don't need to be concerned about the lifetimes of these references. Either they're inferred or elided. Some code doesn't even allow us to specify them. Lifetime annotations are identifiable as lowercase identifiers preceded by a single quote and show up as part of either generic type parameters or a reference type:
fn print<...