Early return
- Rust course
- Beginner
- Lesson 34/115
- 4 min
Return early with the return keyword.
Early return
return leaves the function immediately. It is usually used to handle special or invalid cases at the start and keep the main logic unindented:
fn indirim(tutar: f64, uye: bool) -> f64 {
if tutar <= 0.0 {
return 0.0;
}
if !uye {
return tutar;
}
tutar * 0.9
}Not writing return for the value on the last line is the Rust convention.
Early return with Option
Returning None when a value isn't found is another common use of early return:
fn ilk_cift(sayilar: &[i32]) -> Option<i32> {
for &n in sayilar {
if n % 2 == 0 {
return Some(n);
}
}
None
}
println!("{:?}", ilk_cift(&[3, 7, 8, 10])); // Some(8)You'll see the Option type in detail later.
Practice First even number
Write the ilk_cift(sayilar: &[i32]) -> Option<i32> function above. Print the results for &[3, 7, 8, 10] and &[1, 5] with {:?} on one line.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn ilk_cift(sayilar: &[i32]) -> Option<i32> {
for &n in sayilar {
if n % 2 == 0 {
return Some(n);
}
}
None
}
fn main() {
println!("{:?} {:?}", ilk_cift(&[3, 7, 8, 10]), ilk_cift(&[1, 5]));
}Expected output
Some(8) None
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the main benefit of early returns?
- It saves memory
- Special cases are separated at the start and the main flow isn't nested Correct answer
- It speeds up the code
- It's required
Explanation: Guard clauses let the reader see each condition separately and prevent deep stacks of if-else.
2 Leave now
if b == 0 {
____ None;
}
if b == 0 {
return None;
}
Explanation: return leaves the function immediately with the given value.
3 Code and behavior
| Term | Meaning |
|---|---|
return 0.0; |
Leaves immediately |
tutar * 0.9 (last line) |
Normal return |
return Some(n); |
Leaves once found |
None (last line) |
Not found |