Welcome back to CodeYourCraft! Today, we're diving into one of the exciting features of Rust - Loop Labels. This concept will help you navigate and control loops with greater precision. Let's get started!
Loop labels allow you to jump out of a nested loop from any point in the outer loop. In simpler terms, it lets you break or continue a specific loop from anywhere within its parent loop.
outer_loop: loop {
// code for outer loop
inner_loop: loop {
// code for inner loop
break outer_loop; // exit both loops
continue outer_loop; // skip the rest of the outer loop, start inner loop again
}
}In the above example, outer_loop and inner_loop are the labels for the respective loops. The break and continue statements are used to control the flow of the loops.
The break statement exits the current loop and continues execution with the next statement following the loop. On the other hand, the continue statement skips the current iteration and continues with the next iteration of the same loop.
outer_loop: for i in 1..10 {
inner_loop: for j in 1..10 {
if i * j > 20 {
break outer_loop;
}
println!("{} * {} = {}", i, j, i * j);
}
}In the above example, we're performing a multiplication operation for each combination of i and j within the range of 1 to 10. If the product exceeds 20, the break statement is triggered, and the outer loop is exited.
outer_loop: for i in 1..10 {
inner_loop: for j in 1..10 {
if i == 5 && j == 5 {
continue inner_loop;
}
println!("{} * {} = {}", i, j, i * j);
}
}In this example, we're skipping the multiplication operation when i and j both are 5. This ensures that the number 25 is not printed in the output.
continue statements, as they can result in skipped iterations that may or may not be intended.Which statement is used to skip the current iteration and continue with the next iteration of the same loop?
That's it for today! Loop labels are a powerful tool to control the flow of your loops in Rust. Practice using them in your projects, and you'll be able to write cleaner, more efficient code. Until next time, happy coding! 🚀