Great question! While for loops in Rust and C++ can look superficially similar, there are some nontrivial differences in how they work, especially regarding iteration, ownership, safety, and flexibility. Here’s a detailed comparison:
1. Syntax and Semantics
C++:
C++ has several forms of for loops:
Rust:
Rust’s for loop is always a for-each style:
for x in collection { ... }
There is no classic C-style for loop in Rust.
2. Iteration Protocol
C++:
- The range-based for loop works with anything that has
begin() and end() methods (i.e., is iterable).
- The classic for loop is just syntactic sugar for a while loop.
Rust:
- The for loop works with anything that implements the
IntoIterator trait.
- The loop consumes the iterator unless you explicitly borrow it.
3. Ownership and Borrowing
C++:
Rust:
4. Custom Iterators
C++:
- You can define custom iterators by implementing the iterator interface (with
operator++, operator*, etc.).
- The range-based for loop works with any type that has
begin() and end().
Rust:
- You implement the
Iterator trait for your type.
- The for loop works with anything that implements
IntoIterator.
5. Safety and Lifetime
C++:
- Iterator invalidation is a common source of bugs (e.g., erasing elements while iterating).
- No built-in protection against use-after-free, dangling references, etc.
Rust:
- The borrow checker ensures you cannot have dangling references or use-after-free.
- Mutating a collection while iterating is only allowed in safe ways (e.g., using
drain).
6. Loop Variable Scope
C++:
- The loop variable is scoped to the loop.
Rust:
- Same: the loop variable is scoped to the loop.
7. Nontrivial Example: Consuming vs Borrowing
C++:
std::vector<std::string> v = {"a", "b", "c"};
for (auto s : v) { /* s is a copy */ }
for (auto& s : v) { /* s is a reference */ }
- The vector
v is always usable after the loop.
Rust:
let v = vec!["a".to_string(), "b".to_string(), "c".to_string()];
for s in v { /* s is moved out of v */ }
// v is now invalid (moved)
let v = vec!["a".to_string(), "b".to_string(), "c".to_string()];
for s in &v { /* s is a reference */ }
// v is still valid
- If you iterate by value, the collection is moved and cannot be used after.
- If you iterate by reference, the collection is still usable.
8. No C-style for in Rust
Rust does not have a direct equivalent to:
for (int i = 0; i < n; ++i) { ... }
Instead, you use:
for i in 0..n { ... }
This is more idiomatic and less error-prone (no off-by-one errors, no accidental infinite loops).
9. Parallelism and Safety
- Rust’s iterators can be easily made parallel (with crates like
rayon), and the borrow checker ensures thread safety.
- C++ has parallel algorithms (C++17), but thread safety is not enforced by the language.
Summary Table
| Feature | C++ | Rust |
|---|
| Classic for loop | Yes | No |
| Range-based for | Yes | Yes (only style available) |
| Ownership | No concept | Enforced by compiler |
| Borrowing | Manual (via references) | Enforced by compiler |
| Iterator protocol | begin()/end() | IntoIterator trait |
| Safety | Manual | Enforced (no use-after-free, etc.) |
| Mutating while iterating | Dangerous, can cause UB | Only allowed in safe ways |
| Parallelism | Manual, C++17 parallel algorithms | Easy with crates, thread safety enforced |
Conclusion
Rust’s for loops are more restrictive but safer and more expressive due to ownership and borrowing. C++ for loops are more flexible but less safe, and you must be careful with lifetimes and iterator invalidation.
If you want a specific nontrivial example or code comparison, let me know!