具有分支的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); |
} |