通过例子学习Rust

7 if和else

Rust的if-else分支判断语句类似于C语言。但跟C不同的是,逻辑型条件不需要用小括号括起来,条件后面必须跟一个代码块。 if-else语句也是表达式,每个分支必须返回相同的类型,以保证类型安全。

fn main() { let n = 5i; 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 `int` 10 * n } else { println!(", and is a big number, reduce by two"); // This expression must return an `int` as well n / 2 // TODO ^ Try suppressing this expression with a semicolon }; // ^ Don't forget to put a semicolon here! All the `let` bindings need it println!("{} -> {}", n, big_n); }