chapter ten
10 Lifetimes and interior mutability
This chapter covers
- Types of &str (there's more than one)
- Lifetime annotations - Helping the compiler know how long a reference lives
- Interior mutability - Safe mutability without &mut
It is now time to learn about Rust’s famous lifetimes, used by the compiler to know when variables can be dropped, and how long references last. Usually you don’t need to specify lifetimes in your code, but sometimes the compiler needs a bit of help and will ask you to tell it how long something should last. We are also going to learn how to (safely!) mutate values without needing a mutable reference to do it!
10.1 Types of &str
We've been using &str for most of the book so far. But here's an interesting fact about them: there is actually more than one type of &str. The two ways you'll see a &str are as follows:
- String literals: you make these when you write
let my_str = "I am a &str";. They last for the whole program, because they are written directly into the binary. They have the type&'static str. The'means its lifetime, and string literals have a lifetime calledstatic. - Borrowed
str: This is the regular&strform without a'staticlifetime. If you have aStringand pass a reference to it (a&String), Rust will convert it to a&strwhen you need it. This is thanks to a trait calledDeref. We will learn to useDerefin Chapter 15, but for the moment just remember that you can pass in a&Stringto a function that takes a&str.