ガード
match内の条件文をフィルタリングするために、 ガード を使用することができます。
#[allow(dead_code)]
enum Temperature {
Celsius(i32),
Fahrenheit(i32),
}
fn main() {
let temperature = Temperature::Celsius(35);
// ^ TODO `temperature`の値を変更してみましょう。
match temperature {
Temperature::Celsius(t) if t > 30 => println!("{}C is above 30 Celsius", t),
// ^ `if`とそれに続く条件式がガードです。
Temperature::Celsius(t) => println!("{}C is equal to or below 30 Celsius", t),
Temperature::Fahrenheit(t) if t > 86 => println!("{}F is above 86 Fahrenheit", t),
Temperature::Fahrenheit(t) => println!("{}F is equal to or below 86 Fahrenheit", t),
}
}
パターンが全てカバーされているかどうかを判断する際に、ガード条件は考慮されないことに注意してください。
fn main() {
let number: u8 = 4;
match number {
i if i == 0 => println!("Zero"),
i if i > 0 => println!("Greater than zero"),
// _ => unreachable!("Should never happen."),
// TODO ^ アンコメントしてコンパイルエラーを直してみましょう。
}
}