11 Multiple threads and a lot more

 

This chapter covers

  • The todo! macro to make the compiler quiet for a while
  • Type aliases to create different names but not new types
  • The Cow enum, which allows you to choose to borrow or own data however you want
  • Rc, which allows shared instead of unique ownership
  • Using multiple threads to run many things at the same time

You’re getting pretty good at Rust by now, so it’s time to take a look at some more advanced types. This chapter doesn’t really have a single theme. Instead, we’ll look in turn at some advanced subjects: Cow, type aliases, Rc, and multiple threads. Understanding how multiple threads work is probably the hardest part of this chapter. The famous Cow type (yes, that’s its real name) is a little bit tricky, too. You’ll probably like the Rc (reference counter) type as it gives you a bit of extra flexibility when it comes to Rust’s ownership rules.

11.1 Importing and renaming inside a function

Usually, you write use at the top of the program like this:

use std::cell::{Cell, RefCell};

But we saw that you can do this anywhere, especially in functions with enums that have long names. Here is an example:

11.2 The todo! macro

11.3 Type aliases

11.4 Cow

11.5 Rc

11.5.1 Why Rc exists

11.5.2 Using Rc in practice

11.5.3 Avoiding lifetime annotations with Rc

11.6 Multiple threads