5 Design patterns: Beyond the basics

 

This chapter covers

  • Metaprogramming with macros
  • Implementing the builder pattern in Rust
  • Building fluent interfaces
  • Observing the observer pattern
  • Understanding the command pattern
  • Exploring the newtype pattern

Chapters 2 and 3 introduced the core Rust building blocks: generics, traits, pattern matching, and functional programming features. In this chapter, we’re going to build on what we learned in those chapters by exploring those themes further and examining design patterns in Rust.

Using what we’ve learned, we can start to build more concrete patterns in a way that is consistent with Rust idioms. Although we won’t explore all the possible patterns, I’ll present carefully chosen examples that demonstrate the fundamentals needed to build nearly any design pattern in Rust.

If generics, traits, pattern matching, and closures are the raw ingredients of any design pattern, the patterns in this chapter represent archetypes of nearly any other pattern that combines those features. Before diving right into the patterns themselves, we’ll discuss macros, which aren’t patterns themselves but are often used in advanced design patterns.

5.1 Metaprogramming with macros

 
 
 

5.1.1 A basic declarative macro in Rust

 

5.1.2 When to use macros

 
 
 

5.1.3 Using macros to write mini-DSLs

 
 
 

5.1.4 Using macros for DRY

 

5.2 Optional function arguments

 
 

5.2.1 Examining optional arguments in Python

 
 
 

5.2.2 Examining optional arguments in C++

 
 
 
 

5.2.3 Optional arguments in Rust or the lack thereof

 
 
 

5.2.4 Emulating optional arguments with traits

 
 

5.3 Builder pattern

 

5.3.1 Implementing the builder pattern

 
 
 
 

5.3.2 Enhancing our builder with traits

 
 

5.3.3 Enhancing our builder with macros

 
 
 
 

5.4 Fluent interface pattern

 
 

5.4.1 A fluent builder

 
 
 

5.4.2 Test-driving our fluent builder

 

5.5 Observer pattern

 
 

5.5.1 Why not callbacks?

 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest