Control Flow
Learn to make decisions with if expressions and repeat tasks with various loop types
Learning Objectives
- Use 'if' expressions (and learn why they are expressions)
- Understand 'loop', 'while', and 'for' loops
- Iterate through collections with 'for' and 'range'
if Expressions
In Rust, if is an expression, not just a statement. This means it returns a value.
|
|
Using if in a let Statement
Since if is an expression, we can use it on the right side of a let statement:
|
|
if and else arms must have the same type. You cannot return an integer from one and a string from the other.Repetition with Loops
Rust has three kinds of loops: loop, while, and for.
1. The loop
loop tells Rust to execute a block of code over and over again forever or until you explicitly tell it to stop.
|
|
Returning values from loops:
You can add a value after break to return it from the loop:
|
|
2. The while Loop
Runs as long as a condition is true.
|
|
3. The for Loop
The most common loop in Rust. It’s used to iterate over a collection or a range.
|
|
1..4 is a range from 1 to 3.
1..=4 is a range from 1 to 4.Summary
Today you learned:
ifis an expression and can be used to assign values.loopis for infinite repetition (can return values viabreak).whileis for conditional repetition.foris the safest and most common way to iterate through collections and ranges.
Practice Exercise
- Write a program that prints numbers from 1 to 20, but for multiples of 3 print “Fizz” and for multiples of 5 print “Buzz” (FizzBuzz!).
- Use a
forloop to reverse an array. - Use
loopto find the first power of 2 greater than 1000.
Next Steps
Tomorrow, we’ll cover the most important concept in Rust: Ownership! This is what makes Rust different from every other language.
Quiz
Complete this quiz with a minimum score of 80% to mark Day 5 as complete.
Discussion
Have questions or want to discuss this lesson? Join the conversation below!