Menu
CoddyTech

match と列挙型

Coddyの「Dart開発者のためのRust」コースのレッスン 9/48。

Dartのsealedクラスを使用すると、ライブラリは選択肢の閉じられたファミリーを記述でき、switch式はそのファミリーを網羅的にマッチングできます。Rustのenumは、異なるフィールドを保持できるバリアントを直接宣言します。Readyにはページ数が含まれ、Loadingにはペイロードがありません。マッチングによって適切な挙動が選択され、そのアーム内で関連するデータを利用できるようになります。Dartのクラスパターンはpagesプロパティを読み取りますが、Rustのenumパターンはバリアントを構造分解します。どちらの例も、読み込み状態のためにセンチネル値(マジックナンバー)を必要としません。新しい選択肢を追加したときに未処理のケースを露出させたい場合は、キャッチオール(catch-all)アームを避けてください。このコースでは、ドメインの状態とそれらに必要な挙動を明確にするためにmatchを使用します。

完全に独立したDartプログラム:

sealed class DocumentState {}
class Ready extends DocumentState {
  final int pages;
  Ready(this.pages);
}
class Loading extends DocumentState {}
String describe(DocumentState state) => switch (state) {
  Ready(:final pages) => 'pages=' + pages.toString(),
  Loading() => 'loading',
};
void main() {
  print(describe(Ready(9)));
  print(describe(Loading()));
}

Dartの出力:

pages=9
loading

完全に独立したRustプログラム:

enum DocumentState { Ready(u32), Loading }
fn describe(state: DocumentState) -> String {
    match state {
        DocumentState::Ready(pages) => format!("pages={}", pages),
        DocumentState::Loading => "loading".to_string(),
    }
}
fn main() {
    println!("{}", describe(DocumentState::Ready(9)));
    println!("{}", describe(DocumentState::Loading));
}

Rustの出力:

pages=9
loading
challenge icon

チャレンジ

簡単

1つのアクチュエータコマンドをデコードします。入力は forward amount、back amount、または wait です。量は 0 から 1000 までの整数です。必要なパブリックenum: バリアント Forward(i32)、Back(i32)、および Wait を持つ Command。必要なAPI: pub fn displacement(command: Command) -> i32 は Forward の場合はその量を、Back の場合はその負の値を、Wait の場合はゼロを返します。pub fn active(command: Command) -> bool は、移動量がゼロであっても、Wait の場合のみ false を返します。このenumは Clone, Copy を自動導出するため、提供されているラッパーは同じコマンドを両方の関数に渡すことができます。displacement active を出力します。パブリックAPIを actuator.rs に実装してください。提供されている exercise.rs は有効な入力をパースし、そのAPIを呼び出します。末尾の改行なしで指定されたテキストを返してください。ロックされたドライバーが改行を1つ追加します。API内から標準出力を行わないでください。すべての入力値は提示された範囲を満たします。

必要な公開APIを実装し、exercise::solve(input: &str) -> String から末尾の改行なしで結果を返してください。編集可能なコード内で標準出力を行わないでください。ロックされたドライバーは必要なAPIを独立して検証し、すべての標準入力を読み込んで、返されたテキストに末尾の改行を1つ加えて出力します。

あなたのコードは exercise.rs、actuator.rs に記述します。main.rs には提供された入出力コードが含まれており、編集できません。

自分で試してみよう

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod actuator;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // パブリック API プローブの開始
assert_eq!(actuator::displacement(actuator::Command::Forward(37)), 37);
assert_eq!(actuator::displacement(actuator::Command::Back(37)), -37);
assert_eq!(actuator::displacement(actuator::Command::Wait), 0);
assert!(actuator::active(actuator::Command::Forward(0)));
assert!(actuator::active(actuator::Command::Back(0)));
assert!(!actuator::active(actuator::Command::Wait));
assert_eq!(actuator::displacement(actuator::Command::Forward(37)), 37);
    // パブリック API プローブの終了
    println!("{}", exercise::solve(&input));
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

Dart開発者のためのRustのすべてのレッスン

自分で練習してみよう: Rustオンラインコンパイラ