loop
- Rust course
- Beginner
- Lesson 38/115
- 4 min
Loop forever with loop and exit with break.
loop
loop repeats forever until explicitly breaked. break can return a value; continue skips the rest of the iteration:
let mut n = 0;
let sonuc = loop {
n += 1;
if n % 2 == 0 {
continue;
}
if n > 7 {
break n * 10;
}
};
println!("{sonuc}"); // 90Labeled loops
Labels start with a single quote:
'dis: for i in 1..=3 {
for j in 1..=3 {
if i * j == 4 {
println!("bulundu: {i} x {j}");
break 'dis;
}
}
}loop is common in retry logic: break on success, otherwise try again.
Practice First common multiple
Using loop, find the first positive number divisible by both 4 and 6: start with let mut n = 0;, do n += 1 each iteration and return the value with break n once the condition holds. Print the result.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let mut n = 0;
let sonuc = loop {
n += 1;
if n % 4 == 0 && n % 6 == 0 {
break n;
}
};
println!("{}", sonuc);
}Expected output
12
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is used to leave the outer loop in nested loops?
- break break;
- Always return
- exit()
- A labeled break: break 'dis; Correct answer
Explanation: A loop gets a label written 'name:, and break 'name; ends that loop; continue 'name; works too.
2 Exit with a value
let ilk = loop {
n += 7;
if n % 5 == 0 {
break ____;
}
};
let ilk = loop {
n += 7;
if n % 5 == 0 {
break n;
}
};
Explanation: The value written after break becomes the value of the loop expression.
3 Statement and effect
| Term | Meaning |
|---|---|
loop |
Infinite loop |
break x |
Exits with a value |
continue |
Next iteration |
break 'dis |
Leaves the outer loop |