가드
match
가드를 이용해 각 행을 필터링할 수 있습니다.
#[allow(dead_code)] enum Temperature { Celsius(i32), Fahrenheit(i32), } fn main() { let temperature = Temperature::Celsius(35); // ^ TODO try different values for `temperature` match temperature { Temperature::Celsius(t) if t > 30 => println!("{}C is above 30 Celsius", t), // The `if condition` part ^ is a guard 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 ^ uncomment to fix compilation } }