The if statement allows conditional branching of code.
The expression used as the condition needs to evaluate to a boolean value. If not, the compiler issues an error:
if 1 {
println!("Hi");
}[E0308] Error: mismatched types
╭─[ command_2:1:1 ]
│
1 │ if 1 {
│ ┬
│ ╰── expected `bool`, found integer
───╯Here is a correct conditional expression:
if 1 != 2 {
println!("True");
}True
()Example of chained if/else:
let n = 5;
if n > 10 {
println!("Yes");
} else if n < -20 {
println!("Maybe");
} else {
println!("No");
}No
()10.1.1As an expression¶
if/else statement can be used as an expression:
let n = 11;
let x = if n < 10 { 5.5 } else { -4.1 };
x-4.1We can chain the if/else statements:
let s = "b";
let t = if s == "a" { (1,2) } else if s == "b" { (3,4) } else { (5,6) };
t(3, 4)