Functions and control flow
Write functions, tell statements from expressions, and branch or loop with if, while, for and ranges.
- Return the last expression of a function by leaving off the semicolon.
- Treat if as an expression to produce a value directly.
- Use for with ranges for counted loops and while for condition loops.
- Remember a..b excludes b while a..=b includes it.
In plain English
A function is declared with fn and can return a value; the last expression in a function is its return value when there is no semicolon. A statement does something and returns nothing, while an expression produces a value, which is why an if can be used as an expression that returns a value. if and else choose between branches, loop repeats forever until it breaks, while repeats while a condition holds and for walks over a range or collection. A range is written a..b for a half-open range that includes a but not b, and a..=b for an inclusive range that includes both ends.
Step by step
- 1Write an fn that returns the value of its last expression.
- 2Use if/else if/else as an expression and store the result.
- 3Break out of a loop when a condition is met.
- 4Walk a range with for, choosing 1..4 or 1..=3 depending on whether the end is included.
fn level(minutes: u32) -> u32 {
if minutes < 10 {
1
} else if minutes < 20 {
2
} else {
3
}
}
fn main() {
let level = level(12);
println!("level {}", level);
let mut count = 0;
loop {
count += 1;
if count >= 3 {
break;
}
}
println!("looped {} times", count);
while count < 5 {
count += 1;
}
println!("count now {}", count);
for i in 1..4 {
println!("lesson {}", i);
}
for i in 1..=3 {
println!("inclusive {}", i);
}
}Common mistakes
- Putting a semicolon after the final expression of a function turns it into a statement, so the function returns the unit type instead of your value.
- Writing if as a statement when you need its value forces repeated assignments, when the whole if could be one expression.
- Using 1..5 expecting it to include 5 is wrong, because a..b excludes b; use a..=b to include it.
- Forgetting to break inside a loop that should end makes the loop run forever.
Grade a lesson
Write a function grade(minutes: u32) -> char that returns A when minutes is 10 or less, B when 20 or less, and C otherwise.
fn grade(minutes: u32) -> char {
'C'
}In Rust, what does a function return when its last expression has no semicolon?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.