Menu
CoddyTech

エラーの契約

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

Luaのエラーには文字列以外の値も含められるため、タグ付きテーブルを使うと、pcallの後に失敗の理由を特定できます。エラー列挙型を使ったRustのResultでは、コンパイラーが検査するバリアントを宣言できます。どちらの例も、表示メッセージを解析せずに未対応の形式を分類します。エラーを返したり、発生したエラーを捕捉したりしても、それ以前の変更が自動的に元に戻るわけではありません。状態を持つ操作で拒否時に状態を変更しないことを保証する場合は、確定前に検証するか、意図的に以前の状態に戻してください。ドメイン上の分類と表示を分けておけば、呼び出し側は安定したタグやバリアントに基づいて復旧方法を選べます。想定される無効な入力は、意図的に定めた公開エラー契約で表現してください。

Lua:完全なプログラム

local function check_format(name)
    if name ~= "plain" then error({kind = "unsupported"}) end
end
local ok, problem = pcall(check_format, "binary")
if not ok and problem.kind == "unsupported" then print("format") end

Rust:完全なプログラム

#[derive(Debug)]
enum FormatError { Unsupported }
fn check_format(name: &str) -> Result<(), FormatError> {
    if name == "plain" { Ok(()) } else { Err(FormatError::Unsupported) }
}
fn main() {
    match check_format("binary") {
        Ok(()) => println!("ready"),
        Err(FormatError::Unsupported) => println!("format"),
    }
}

失敗値や保護呼び出しは、トランザクションのロールバック機構ではありません。

challenge icon

チャレンジ

簡単

account.rs に、Debug と PartialEq を導出する公開バリアント NonPositive と Insufficient を持つ DebitError、および pub fn debit(balance: &mut i32, amount: i32) -> Result<i32, DebitError> を実装してください。開始時の残高は0以上で、算術演算は i32 の範囲内に収まります。金額が0以下の場合は NonPositive を返して拒否し、それ以外の場合、金額が残高を超えていれば Insufficient を返して拒否します。失敗した場合、残高は変更しません。成功した場合は金額を差し引き、新しい残高を返します。入力は開始残高に続いて引き落とし額が並びます。solve はそれらを順番に適用し、final|statuses を返します。ステータスは ok:new、nonpositive、または insufficient で、カンマ区切りです。引き落とし額がない場合、接尾辞は空になります。

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

コードは exercise.rs と account.rs に記述してください。main.rs には提供された入出力コードが含まれており、編集できません。

自分で試してみよう

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod account;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // 公開APIの検証開始
let mut balance = 37;
assert_eq!(account::debit(&mut balance, 12), Ok(25));
assert_eq!(account::debit(&mut balance, 26), Err(account::DebitError::Insufficient));
assert_eq!(balance, 25);
assert_eq!(account::debit(&mut balance, -4), Err(account::DebitError::NonPositive));
assert_eq!(balance, 25);
assert_eq!(account::debit(&mut balance, 0), Err(account::DebitError::NonPositive));
assert_eq!(balance, 25);
assert_eq!(account::debit(&mut balance, 25), Ok(0));
assert_eq!(account::debit(&mut balance, 1), Err(account::DebitError::Insufficient));
assert_eq!(balance, 0);

    // 公開APIの検証終了
    println!("{}", exercise::solve(&input));
}
quiz icon腕試し

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

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

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