Rust if/else语句

任何编程语言都有自己方法来修改控制流的主要部分: if/else, for, 以及其它。让我们来谈谈这些在Rust中。

if/else

具有分支的if-else语句类似于其他语言。 不同于其它,布尔条件不需要由括号包围,并且每个条件后跟一个块。if-else 条件等都是表达式,以及所有分支必须返还相同种类。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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);
}

联系我们

邮箱 626512443@qq.com
电话 18611320371(微信)
QQ群 235681453

Copyright © 2015-2024

备案号:京ICP备15003423号-3