abortunwind

上一节说明了错误处理机制 panic。可以根据 panic 设置有条件地编译不同的代码路径。当前可用的值是 unwindabort

在之前的柠檬水示例的基础上,我们显式地使用 panic 策略来执行不同的代码行。

fn drink(beverage: &str) {
    // You shouldn't drink too much sugary beverages.
    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");
}

可以使用 abortunwind 从命令行设置 panic 策略。

rustc  lemonade.rs -C panic=abort