問題一覧に戻る
上級ジェネリクス
問題98: 型状態パターン

型状態パターンはRustの型システムを使ってコンパイル時に状態マシンをエンコードします。無効な状態遷移は実行時バグではなくコンパイルエラーになります。各状態は異なる型で、メソッドは適切な状態でのみ利用可能です。このパターンはプロトコルが正しく守られることを保証し、バグのクラス全体を排除します。ビルダーパターンやネットワークプロトコルで広く使用されます。

// 型状態パターン
struct <S> {
content: String,
state: std::marker::PhantomData<S>,
}

// 状態を表す型
struct Draft;
struct ;

// Draft状態の実装
impl Request<> {
fn new() -> Self {
Request {
content: String::new(),
state: std::marker::,
}
}

// 状態遷移
fn send(self) -> Request<> {
Request {
content: self.content,
state: std::marker::PhantomData,
}
}
}

fn main() {
let req = Request::new();
let sent = req.();
// req.send(); // Error: moved
}