liveBook · Manning

Builder pattern

As explained in Learn Rust in a Month of Lunches

The builder pattern is a construction pattern that uses a separate configurable object to assemble and validate the parameters needed to create another type.

The builder pattern creates a value through small configuration steps instead of one call with many arguments. Start with defaults, change only what you need, and chain the methods together. This is especially useful when a type has many fields but most callers want the default values. section 15.2 section 15.1

Change a few defaults

`let character = Character::default().height(180).weight(60).name("Bobby");` starts with a default character, then changes three fields. Each method takes `mut self`, changes one field, and returns `Self`. Returning the value makes the next method call possible. section 15.2.1

A chain can also end with a check. A `build()` method can return `Result`: `Ok` when the settings are acceptable, or `Err` when they are not. For example, it can reject excessive height or weight and a forbidden word in a name. But checking a flag on the finished type does not force other callers to perform that check. section 15.2.2

For stronger control, use a separate builder type. Its settings can be edited, but it is not the finished type. A `try_build()` method creates the finished value only when validation succeeds; functions requiring that value cannot accept the builder in its place. section 15.2.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Works through methods that consume and return `Self`, final validation, and a separate builder type after showing why a flag is insufficient.
Examples
Uses a default character with configurable name, height, and weight, then checks invalid settings before construction.
What it assumes
Starts with structs and default values, then explains how taking and returning `Self` enables chained methods.
What you can do after
Build it from scratch using configurable methods and a separate builder type when invalid settings must not produce the finished type.
How it connects
Connects the Default trait and method chaining to ownership, Result-based validation, and distinct struct types.

Also explained in

Compare how 6 books explain builder pattern →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.