12 More on closures, generics, and threads

 

This chapter covers

  • Closures in functions
  • impl Trait as another way to use generics
  • Arc, which is like Rc but thread-safe
  • Scoped threads, threads that only live inside a scope
  • Using channels to send messages, even across threads

This chapter is a bit like the last one: lots of new ideas that are tricky to understand at first. The first section on closures as arguments in functions is probably the hardest but continues what we learned in the last chapter about the three types of closures. Fortunately, the rest of the chapter is made up of similar things to what you’ve learned before. impl Trait is like regular generics but easier to write, Arc is like Rc, and scoped threads are like threads but easier to use; you’ll understand the channel examples fairly easily too because you already know how multiple threads work.

12.1 Closures as arguments

Closures are great. We know how to make our own, but what about closures as arguments in functions? Arguments need to have a type, but what exactly is a closure’s type?

12.1.1 Some simple closures

12.1.2 The relationship between FnOnce, FnMut, and Fn

12.1.3 Closures are all unique

12.1.4 A closure example

12.2 impl Trait

12.2.1 Regular generics compared to impl Trait

12.2.2 Returning closures with impl Trait

12.3 Arc

12.4 Scoped threads