chapter twelve

12 More on closures, generics, and threads

 

This chapter covers

  • Closures in functions
  • Impl trait - Another way to use generics
  • Arc - Like Rc, but thread safe
  • Scoped threads - Threads that only live inside a scope
  • Channels - Sending 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 closures in functions section is probably the hardest, but continues what we learned 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, scoped threads are like threads but easier to use, and the channel examples you’ll understand fairly easily 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

12.5 Channels

12.5.1 Channel basics

12.5.2 Implementing a channel

12.6 Summary