Introduction
In this lab, we learn about using if-else statements in Rust. Similar to other programming languages, if-else statements in Rust don't require parentheses around the condition and each condition is followed by a block of code. These conditionals are expressions, so all branches must return the same type. Within the code example provided, we first check if the variable n is less than 0, and if so, it prints that n is negative. If n is not less than 0, we then check if it is greater than 0 and print that n is positive. Finally, if none of the previous conditions are met, we print that n is zero. Another example demonstrates how the if-else statement can be used as an expression to assign a new value to the variable big_n. If n is between -10 and 10, it prints that n is a small number and assigns 10 * n to big_n. Otherwise, it prints that n is a big number and assigns n / 2 to big_n. The final output of n and big_n is printed at the end.
Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use
main.rs, compile and run it withrustc main.rs && ./main.
if/else
Branching with if-else is similar to other languages. Unlike many of them, the boolean condition doesn't need to be surrounded by parentheses, and each condition is followed by a block. if-else conditionals are expressions, and, all branches must return the same type.
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, halve the number");
// 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);
}
Summary
Congratulations! You have completed the If/Else lab. You can practice more labs in LabEx to improve your skills.