15 Default, the builder pattern, and Deref

 

This chapter covers

  • Using the Default trait
  • Using the builder pattern to control how your types are generated
  • Using Deref and DerefMut to steal the methods of other types to use in your own

This chapter is a fun one. You’ll learn the builder pattern, which lets you declare variables by chaining method after method instead of writing all the parameters for a struct. It’s especially good for writing code that other people might use because you can control which parts they can touch and which they can’t. The Deref trait that you’ll learn later in the chapter lets you make your own types that hold all the methods of another type for free. This allows you to easily make types that hold someone else’s type inside, to which you can add your own methods on top.

15.1 Implementing Default

You can implement the Default trait to give values to a struct or enum that you think will be most common or represent the type’s base state. The builder pattern in the next section works nicely with this to let users easily make any changes after starting with default values.

15.2 The builder pattern

15.2.1 Writing builder methods

15.2.2 Adding a final check to the builder pattern

15.2.3 Making the builder pattern more rigorous

15.3 Deref and DerefMut

15.3.1 Deref basics

15.3.2 Implementing Deref

15.3.3 Implementing DerefMut

15.3.4 Using Deref the wrong way

Summary