0
0
Rustprogramming~20 mins

Loop labels in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Loop Labels in Rust
๐Ÿ“– Scenario: Imagine you are organizing a treasure hunt game. You have several boxes, and each box contains several smaller boxes. You want to find a special item inside these nested boxes. To do this, you need to check each smaller box inside each big box. Sometimes, when you find the item, you want to stop searching immediately, even if you are inside a nested loop.
๐ŸŽฏ Goal: You will write a Rust program that uses loop labels to break out of nested loops when a special item is found.
๐Ÿ“‹ What You'll Learn
Create a nested loop structure with two loops: an outer loop labeled 'outer and an inner loop labeled 'inner.
Use break 'outer to exit both loops when a condition is met.
Print messages to show the progress of the search and when the item is found.
๐Ÿ’ก Why This Matters
๐ŸŒ Real World
Loop labels help when you have nested tasks and want to stop or skip outer tasks from inside inner tasks, like searching in nested boxes or menus.
๐Ÿ’ผ Career
Understanding loop labels is useful for writing clear and efficient Rust code, especially in systems programming, game development, and complex data processing.
Progress0 / 4 steps
1
Create nested loops with labels
Write a nested loop structure in Rust with an outer loop labeled 'outer and an inner loop labeled 'inner. Inside the inner loop, print "Checking smaller box". Inside the outer loop, print "Checking big box" before the inner loop starts.
Rust
Need a hint?

Use 'outer: loop { ... } to label the outer loop and 'inner: loop { ... } for the inner loop. Use println! to print messages.

2
Add a counter to track smaller boxes
Create a variable called smaller_box_count and set it to 0 before the outer loop. Inside the inner loop, increase smaller_box_count by 1 each time you check a smaller box.
Rust
Need a hint?

Declare smaller_box_count as mutable with let mut. Increase it inside the inner loop.

3
Use loop labels to break out when item is found
Inside the inner loop, add an if statement that checks if smaller_box_count equals 3. If true, print "Item found!" and use break 'outer to stop both loops.
Rust
Need a hint?

Use if smaller_box_count == 3 to check the count. Use break 'outer to exit both loops.

4
Print the total smaller boxes checked
After the loops, print "Total smaller boxes checked: {smaller_box_count}" using an f-string style with println!.
Rust
Need a hint?

Use println!("Total smaller boxes checked: {}", smaller_box_count); to show the final count.