Branching on a condition
Branching on a condition is done with a common if, if else, or if else if else construct, as in this example:
// from Chapter 3/code/ifelse.rs
fn main() {
let dead = false;
let health = 48;
if dead {
println!("Game over!");
return;
}
if dead {
println!("Game over!");
return;
} else {
println!("You still have a chance to win!");
}
if health >= 50 {
println!("Continue to fight!");
} else if health >= 20 {
println!("Stop the battle and gain strength!");
} else {
println!("Hide and try to recover!");
}
} This gives the following output:
You still have a chance to win!Stop the battle and gain strength!
The condition after the if statement has to be a Boolean. However, unlike in C, the condition must not be enclosed in parentheses. Code blocks surrounded by { } (curly braces) are needed after the if, else, or else if statement. The first example also shows that we can get out of a function...