Rustでのif式
Rustではif分岐は式として扱い、値を返すことができる。
let
による変数束縛の際には;
をつける。
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`.
// この式は`i32`を返す。
10 * n
} else {
println!(", and is a big number, halve the number");
// This expression must return an `i32` as well.
// ここでも返り値の型は`i32`でなくてはならない。
n / 2
};
// ここにセミコロンを付けるのを忘れないように!
// `let`による変数束縛の際には必ず必要です!
println!("{} -> {}", n, big_n);
}