πŸ”€
World 3 Β· Building Blocks

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! 😎");
}
New word A condition is a question that is either 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.” πŸŽ‰

Think of it like this… 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! ✨

Try this! Change 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. πŸ”€

You learned… 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! πŸ”