Making Choices (if/else)
Every day you make choices. If itβs raining, you grab an umbrella. Else (otherwise),
you wear your sunglasses. Your code can make choices the same way, using if and
else! π
The if and else fork in the road
An if checks a question that is either true or false. If itβs true, Rust runs
the code in the first set of curly braces. If itβs false, Rust runs the else part
instead.
if raining {
println!("Bring an umbrella! β");
} else {
println!("Wear sunglasses! π");
}
true or
false. if uses it to decide which path to take.
More than two choices: else if
What if there are several possibilities? You can add else if to check more questions
in a row. Rust tries them top to bottom and runs the first one thatβs true.
The number 42 isnβt bigger than 100, but it IS bigger than 10, so Rust printed
βThatβs a big number.β π
if / else if / else is like a "choose your own
adventure" book. You answer a question and it sends you to a different page. π
if can hand back a value
Hereβs a neat trick: an if can also give back a value you store in a box. Just make
sure both paths give back the same kind of thing.
Since 9 is less than 12, the if handed back "child" and we stored it in
ticket. Pretty handy! β¨
number to 5 in the first program and press
βΆ Run. Which line prints now? Then try 500!
Quick quiz
When does the code inside an if run?
Right! The if block runs only when its condition is true. π
if runs code when a condition is true, else
runs otherwise, and else if checks more choices. An if can
even hand back a value! Next up: doing things over and over with loops! π