Rust if/else語句
if/else
具有分支的if-else語句類似於其他語言。 不同於其它,布爾條件不需要由括號包圍,並且每個條件後跟一個塊。if-else 條件等都是表達式,以及所有分支必須返還相同種類。
fn main() { let n = 5; if n < 0 { print!("{} is negative", n); } else if n > 0 { print!("{} is positive", n); } else { print!("{} is zero", n); } let big_n = if n < 10 && n > -10 { println!(", and is a small number, increase ten-fold"); // This expression returns an `i32`. 10 * n } else { println!(", and is a big number, reduce by two"); // This expression must return an `i32` as well. n / 2 // TODO ^ Try suppressing this expression with a semicolon. }; // ^ Don't forget to put a semicolon here! All `let` bindings need it. println!("{} -> {}", n, big_n); }