How to Write Fluent APIs (Method Chaining) in Rust
You write fluent APIs in Rust by defining methods that return Self or &mut Self to enable chaining. Define a struct, implement methods that take &mut self and return &mut Self, then call them sequentially on the same instance.
struct Builder {
value: i32,
}
impl Builder {
fn new() -> Self {
Builder { value: 0 }
}
fn add(mut self, n: i32) -> Self {
self.value += n;
self
}
fn build(self) -> i32 {
self.value
}
}
fn main() {
let result = Builder::new().add(10).add(20).build();
println!("{result}"); // 30
}