MARY.WIN

RUSTY — DESIGN PATTERNS — 02

Builder:
thread::Builder, and why you can use it once

Pattern 2 of 12 · In the life of one value: made.
Part of Rust design patterns.

Learning question: What does a builder give you that a constructor with many arguments does not, and what does Rust add?

Starting a thread has options, and most callers want none of them. This article reads the type std uses to offer them, std::thread::Builder: its three fields, its option methods, and the method that ends the building.

Scope. We read library/std/src/thread/builder.rs at Rust 1.100.0 [S3]. We do not cover scoped threads or what a stack size should be. You need structs, methods and closures. The pattern's parts are named as in Design Patterns [S1, ch. 3, "Builder"].

A builder asked to do two jobs

Example 1 makes a builder, names it, and then tries to spawn from the original.

Example 1. Does not compile (compile-fail/cf02_builder.rs)

let builder = thread::Builder::new();
let named = builder.name("indexer".to_string());
let handle = builder.spawn(|| {}).unwrap();

The binding builder was created on the first line and regarded itself as a permanent fixture, like a ladle that expects to go back on its hook. On the second line it was asked for a name and gave one. On the third it was asked to spawn. The compiler reported that it had been moved on the second line and was not there to ask.

OUTPUT
error[E0382]: use of moved value: `builder`
 --> cf02_builder.rs:6:18
  |
4 |     let builder = thread::Builder::new();
  |         ------- move occurs because `builder` has type `Builder`, which does not implement the `Copy` trait
5 |     let named = builder.name("indexer".to_string());
  |                 ------- value moved here
6 |     let handle = builder.spawn(|| {}).unwrap();
  |                  ^^^^^^^ value used here after move

Predict

Before reading on: look at the error and guess the signature of name. Does it take &mut self or self? What must it return for the usual chained style to work?

Name the parts

Role in the pattern [S1] In std Where [S3]
Builder and ConcreteBuilder pub struct Builder builder.rs line 49
Steps name, stack_size lines 107 and 130
The finishing step spawn line 185
Product JoinHandle<T>, and the running thread returned by spawn
Director your code the call chain

How are the options collected?

A function with one required argument and several optional ones forces every caller to spell out the options they do not care about. Thankfully, there's a simpler way: collect the options in a value. Take a look at Example 2.

Example 2. The builder and its steps (library/std/src/thread/builder.rs, lines 49 to 56, 107 to 110, 130 to 133 and 185, attributes and doc comments removed [S3])

pub struct Builder {
    pub(super) name: Option<String>,
    pub(super) stack_size: Option<usize>,
    pub(super) no_hooks: bool,
}

pub fn name(mut self, name: String) -> Builder {
    self.name = Some(name);
    self
}

pub fn stack_size(mut self, size: usize) -> Builder {
    self.stack_size = Some(size);
    self
}

pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>>

The struct is three fields, two of them Option, so "not chosen" is a value. Each step takes mut self, sets one field, and returns the builder. That is the answer to the prediction: self, by value, returning Builder. spawn also takes self, and returns the product inside an io::Result, because the operating system can decline to start a thread.

Who owns the thread::Builder on each line: three builder values, each moved by the next call, and the JoinHandle that spawn returns The diagram has one column per value. Each call in the chain uses up the builder it was called on and yields the next, and spawn yields a JoinHandle and no builder at all.

You can also skip the builder. thread::spawn(f) (library/std/src/thread/functions.rs, line 125) is the form for callers who want no options, and its documentation says it panics if the operating system fails to create the thread, where Builder::spawn returns an error.

What transfers, and what does not

Fluent setters that return $this are the PHP version, and the reading experience is the same. Two things do not transfer. The book's Builder has an abstract interface with several concrete builders and a director that drives them [S1]; thread::Builder is one concrete type and your call chain is the director, so half the participants are absent here, and I'd call that an honest simplification and not a different pattern. And a PHP builder can be configured further after build() because both names point at one object. Here the builder is gone.

Is "used once" a feature?

The Rust patterns book says Builder is especially useful in Rust because of the ownership model and the type system [S2, ch. 5, "Builder"], and Example 1 is the plainest case of it: a consumed builder cannot be half-reused by accident. It also cannot be kept as a template and spawned from twice, and whether that is protection or an inconvenience depends on which of those you were trying to do, since some builders take &mut self and can be reused, and std's own process::Command is one of them (arg(&mut self, ..), library/std/src/process.rs line 749). When you write your own, which mistake is worse in your program: reusing a configured builder by accident, or not being able to?

Practice tier: compiler. The move rule does the enforcing. You read the diagnostic.

Testing

The claim is that an option set on the builder reaches the product. Example 3 would fail if name were ignored.

Example 3. The name arrives (tests/p02_builder_thread.rs)

#[test]
fn the_named_option_reaches_the_product() {
    let handle = thread::Builder::new()
        .name("indexer".to_string())
        .stack_size(64 * 1024)
        .spawn(|| thread::current().name().map(str::to_owned))
        .expect("the operating system refused to start a thread");
    assert_eq!(handle.join().unwrap().as_deref(), Some("indexer"));
}

It passed on rustc 1.100.0. A second test confirms that a thread from thread::spawn has no name.

Retrieve

  1. Why did Example 1 fail on line 6 and not on line 5?
  2. What does spawn return that name does not, and why is it wrapped in a Result?

Typestate comes back to "each step returns a value" and changes one thing: the value returned has a different type.

TL;DR

std::thread::Builder is a struct of optional settings. name and stack_size each take the builder by value and return it; spawn takes it by value and returns io::Result<JoinHandle<T>>. Because every step moves the builder, each configured builder can be used exactly once, and the compiler says so with E0382.

The sources.

Each article names its sources in brackets, with the file, chapter or line to look at. Line numbers are for the tag or commit each article names and will move. Each article says which toolchain its tests passed on: rustc 1.100.0 for eleven of them, rustc 1.97.0 on Linux for Adapter.

SOURCES — 5
  • [S1] Gamma, Helm, Johnson, Vlissides, Design Patterns, ch. 3, "Builder" (Intent, Participants).
  • [S2] Evan Williams, Design Patterns and Best Practices in Rust (Packt, 2026), ch. 5, "Builder".
  • [S3] rust-lang/rust at tag 1.100.0: library/std/src/thread/builder.rs, library/std/src/thread/functions.rs, library/std/src/process.rs, read 2026-11-29.
  • Compiler output is copied from compile-fail/cf02_builder.stderr, with the trailing summary lines removed.
  • PHP manual, "Objects and references", https://www.php.net/manual/en/language.oop5.references.php, read 2026-11-29: an object variable holds an identifier, and passing or assigning it copies the identifier, which points to the same object.
NOT CHECKED — 3
  • That thread::spawn panics when the operating system cannot create a thread comes from its documentation. No test makes that happen; the second test covers only the missing name.
  • That process::Command can be reused is read from the signature of arg. Reuse was not tested.
  • The attributions to *Design Patterns* (chapter 3) and to Williams (chapter 5) were not checked against the books again for this page.