Rust if/else語句
任何編程語言都有自己方法來修改控制流的主要部分: if/else, for, 以及其它。讓我們來談談這些在Rust中。
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);
}
0 條評論,你可以發表評論,我們會進行改進
