10 Lifetimes and interior mutability

 

This chapter covers

  • Types of &str (there’s more than one)
  • Using lifetime annotations to help the compiler know how long a reference lives
  • Using interior mutability, which provides 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 called static.
  • Borrowed str—This is the regular &str form without a 'static lifetime. If you have a String and pass a reference to it (a &String), Rust will convert it to a &str when you need it. This is thanks to a trait called Deref. We will learn to use Deref in chapter 15, but, for the moment, just remember that you can pass in a &String to a function that takes a &str.

10.2 Lifetime annotations

10.2.1 Lifetimes in functions

10.2.2 Lifetime annotations in types

10.2.3 The anonymous lifetime

10.3 Interior mutability

10.3.1 Cell

10.3.2 RefCell

10.3.3 Mutex