Rust
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Ownership and Borrowing
-
Section 4: Structuring Data
-
Section 5: Collections and Error Handling
-
Section 6: Traits and Generics
-
Section 7: Concurrency
-
Section 8: Building for the Web
-
Section 9: Memory and Performance
-
Section 10: More Standard Library and Ecosystem
-
Section 11: Advanced Rust
-
Section 12: Rust for Systems and WebAssembly
-
Section 13: Tooling and Best Practices
-
Section 14: Data Structures and Algorithms in Rust
-
Section 15: Practical Projects
-
Section 16: Interview Practice
-
Section 17: std::collections In Depth
-
Section 18: std::io and std::fs In Depth
-
Section 19: std::net
-
Section 20: std::option and std::result In Depth
-
Section 21: std::iter In Depth
-
Section 22: std::sync In Depth
-
Section 23: std::string and std::str
-
Section 24: Cargo and Crates.io Ecosystem
-
Section 25: Popular Crates Ecosystem
-
Section 26: Rust Memory Model Deep Dive
-
Section 27: More Practice Exercises
-
Section 28: More Interview Practice
-
Section 29: Async Rust Deep Dive
-
Section 30: Tokio Ecosystem In Depth
-
Section 31: Error Handling Ecosystem Deep Dive
-
Section 32: Serde In Depth
-
Section 33: Web Development with Rust Deep Dive
-
Section 34: Database Access Ecosystem
-
Section 35: Rust for Embedded Systems Deep Dive
-
Section 36: Rust Macros In Depth
-
Section 37: Advanced Trait System
-
Section 38: Unsafe Rust In Depth
-
Section 39: Rust CLI Development
-
Section 40: Testing Ecosystem Deep Dive
-
Section 41: WebAssembly Deep Dive
-
Section 42: Rust Design Patterns
-
Section 43: More Data Structures in Rust
-
Section 44: Final Practice Projects
-
Section 45: Rust Performance Optimization
-
Section 46: Rust Ecosystem Tooling
-
Section 47: More Interview and Review
9: Loops: loop, while, for
Why is there a specific loop keyword instead of just using while true?
If you're coming from C++ or Java, your instinct is probably to just write while true { ... }. While that works in Rust, the loop keyword is there for a very specific reason: it tells the compiler that this block is intended to run forever unless a break is hit.
The real magic happens with type checking. If you use while true, the compiler isn't always sure if the loop will ever terminate. With loop, the compiler knows for a fact that any code following the loop is unreachable unless there's a break. I usually reach for loop when I'm building things like a main game loop or a server listener where the loop is the primary driver of the application.
Can I actually get a value out of a loop?
This is one of my favorite "hidden" features of Rust. You can actually use break to return a value from a loop block and assign it to a variable. You can't do this with while or for loops, which is another reason why loop is so powerful.
Imagine you're polling a sensor or waiting for a specific piece of data from a network socket. Instead of declaring a mutable variable outside the loop and updating it inside, you can just do this:
fn find_ready_signal() -> bool {
let signal = loop {
if check_sensor() == "READY" {
break true; // We found it! Return true from the loop
}
if check_sensor() == "ERROR" {
break false; // Something went wrong, return false
}
// Just keep waiting...
};
signal // Now we use the value the loop gave us
}
Why doesn't Rust have the classic for(i=0; i<10; i++) syntax?
I know it feels weird at first, but Rust ditches the C-style for loop to avoid those annoying "off-by-one" errors we've all spent hours debugging. Instead, Rust uses iterators. When you write for i in 0..10, you're actually creating a Range object that the loop iterates over.
If you need the index and the value from a collection, don't try to manage a counter manually. Use the .enumerate() method. It's cleaner and much harder to mess up:
let tasks = vec!["Clean room", "Write code", "Buy milk"];
for (index, task) in tasks.iter().enumerate() {
println!("Task #{}: {}", index + 1, task);
}
I've found that once you get used to this, going back to manual index management feels like walking a tightrope without a net.
When should I use while let instead of a standard while loop?
You'll see while let a lot in professional Rust code. It's essentially a shorthand for "keep looping as long as this pattern matches." It's incredibly useful when you're dealing with Option or Result types.
For example, if you have a Vec acting as a stack and you want to process it until it's empty, while let is your best friend:
let mut stack = vec![1, 2, 3];
// Keep popping values as long as pop() returns Some(value)
while let Some(top) = stack.pop() {
println!("Processing: {}", top);
}
// The loop automatically stops when pop() returns None
Using a standard while here would require you to manually check stack.is_empty() and then call .unwrap() or handle the None case inside the loop, which is just extra boilerplate you don't need.
π Practical Task
Build a Robust Retry-Logic System
You are writing a piece of software that needs to fetch a configuration file from a remote server. However, the server is "flaky"βit often fails before finally succeeding. Your goal is to implement a retry mechanism using the loops you've learned.
Requirements:
- Create a function
fetch_config()that randomly returns eitherOk("Config Data")orErr("Connection Failed"). - In your
mainfunction, use aloopto attempt to callfetch_config(). - If the call fails, print a warning and increment a retry counter.
- If the call succeeds,
breakthe loop and return the successful data. - If the retry counter reaches 5 attempts without success,
breakthe loop and print a final "Maximum retries reached" error message. - Use the
loop's ability to return a value to store the final result (either the config data or a failure message) into a variable before printing it to the console.
There are no comments for now.