Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Constructor Patterns
构造器模式

What you’ll learn: How Rust replaces Java constructors with associated functions, Default, and builders.
本章将学习: Rust 如何用关联函数、Default 和 builder 模式,替代 Java 风格的构造器。

Difficulty: 🟢 Beginner
难度: 🟢 初级

Rust does not have constructors in the Java sense. Instead, types usually expose associated functions such as new.
Rust 没有 Java 意义上的构造器,类型通常通过关联函数来暴露初始化入口,最常见的名字就是 new

A Basic new
一个基本的 new

#![allow(unused)]
fn main() {
struct Config {
    host: String,
    port: u16,
}

impl Config {
    fn new(host: String, port: u16) -> Self {
        Self { host, port }
    }
}
}

This is explicit and boring, which is usually a good thing.
这种写法非常直白,也有点朴素,但大多数时候这恰恰是好事。

Default
Default

#![allow(unused)]
fn main() {
#[derive(Default)]
struct RetryPolicy {
    max_retries: u32,
}
}

Default is a natural fit for types that have sensible baseline values.
只要一个类型存在合理的默认值,Default 就很合适。

Builder Pattern
builder 模式

Builders are useful when:
下面这些情况就适合上 builder:

  • there are many optional fields
    可选字段很多。
  • construction needs validation
    构造过程需要校验。
  • call sites should read like configuration
    调用点希望看起来像配置声明。
#![allow(unused)]
fn main() {
struct ClientBuilder {
    timeout_ms: u64,
}

impl ClientBuilder {
    fn new() -> Self {
        Self { timeout_ms: 1000 }
    }

    fn timeout_ms(mut self, timeout_ms: u64) -> Self {
        self.timeout_ms = timeout_ms;
        self
    }
}
}

Guidance
选择建议

  • use new for ordinary construction
    普通初始化用 new
  • use Default for sensible zero-argument initialization
    零参数初始化合理时,用 Default
  • use builders when option count and readability demand them
    可选项太多、又想保证可读性时,用 builder。

Rust construction is less magical than Java frameworks, but the trade-off is simpler reasoning at call sites.
Rust 的构造方式没有 Java 框架那种魔法感,但换来的好处是:调用点更容易读,也更容易推理。