liveBook · Manning

Fluent interface

As explained in Idiomatic Rust

A fluent interface is an API style in which chained method calls express a sequence of operations through return values designed for further chaining.

A fluent interface expresses a sequence of operations through chained method calls. Each method returns a value that provides the next operation, and a final call terminates the chain. The pattern builds on the builder pattern and appears in Rust’s Iterator trait. section 5.4 section 5.8

Rust implements chaining through return types. Iterator::map returns another Map iterator, so another map call can continue the chain. The returned type carries the next available operations. section 5.4

A fluent builder

A builder can return a new builder from each assignment method: let bicycle = Bicycle::builder() .with_make("Trek") .with_model("Madone") .with_size(52) .with_color("purple") .build(); Here, each with_* method returns Self, allowing the next call; build ends the operation and produces the bicycle. section 5.4.1 section 5.4.2

These builder methods take self rather than &mut self, consuming the previous builder. Each call constructs a new builder and inner Bicycle, using struct spread syntax to preserve unchanged fields. This approach works with owned values but not references. section 5.4.1

fn map<B, F>(self, f: F) -> Map<Self, F> where
    F: FnMut(Self::Item) -> B { ... }

Inspect the Iterator::map signature to see how a concrete return type enables another operation in the chain. section 5.4

How Idiomatic Rust covers it

How deep it goes
Explains return types, Iterator::map, consuming self, struct spread, and fluent builder construction, but does not develop broader alternatives.
Examples
Demonstrates Iterator::map and a Bicycle builder configured with make, model, size, color, and build.
What it assumes
Assumes familiarity with Rust generics, traits, and ownership while teaching fluent chaining through Iterator and builder examples.
What you can do after
Apply it via Rust methods that return a chainable type, including consuming builder methods and a terminating build operation.
How it connects
Connects method chaining with the builder pattern, Iterator trait, ownership, struct spread syntax, and macros.

Also explained in

Compare how 4 books explain fluent interface →

Related concepts

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