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

abortunwind

前のセクションでは、エラー処理メカニズムである panic を説明しました。 panic の設定に基づいて、異なるコードパスを条件付きでコンパイルできます。現在利用可能な値は unwindabort です。

先ほどのレモネードの例を土台にして、panic 戦略を明示的に使用し、異なる行のコードを実行します。

fn drink(beverage: &str) {
    // 砂糖入りの飲み物を飲み過ぎてはいけません。
    if beverage == "lemonade" {
        if cfg!(panic = "abort") {
            println!("This is not your party. Run!!!!");
        } else {
            println!("Spit it out!!!!");
        }
    } else {
        println!("Some refreshing {} is all I need.", beverage);
    }
}

fn main() {
    drink("water");
    drink("lemonade");
}

次は、drink() の書き換えに焦点を当て、unwind キーワードを明示的に使用する別の例です。

#[cfg(panic = "unwind")]
fn ah() {
    println!("Spit it out!!!!");
}

#[cfg(not(panic = "unwind"))]
fn ah() {
    println!("This is not your party. Run!!!!");
}

fn drink(beverage: &str) {
    if beverage == "lemonade" {
        ah();
    } else {
        println!("Some refreshing {} is all I need.", beverage);
    }
}

fn main() {
    drink("water");
    drink("lemonade");
}

panic 戦略は、コマンドラインから abort または unwind を使用して設定できます。

rustc  lemonade.rs -C panic=abort