November 2017
Intermediate to advanced
264 pages
5h 45m
English
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 ...
Read now
Unlock full access