In Rust, we can loop in multiple ways. It works just like in other languages, but we need to keep the ownership model in mind. Here are the types of loops supported by Rust.
loop | Infinite or manual-control |
while | Condition-based |
for | Idiomatic, iterator-based |
while let | Pattern matching loops |
| Iterator methods | Functional, expressive |
And here are the Iterator methods
| Method | Ownership | Type yielded |
|---|
iter() | borrowed | &T |
into_iter() | moved | T |
iter_mut() | mutably borrowed | &mut T |
And all of them are easy to understand. lets look at the examples without much explaination.



Note: vec is no longer usable here — it’s been moved!

Note: vec is still usable — only borrowed


Ownership: .pop() moves the value out of the vec — you get T, not &T. So top owns each popped value.





Note: vec is no longer accessible here. The line println!("{:?}", vec); will cause a compile-time error: value moved. Once you use into_iter(), the Vec itself is moved. After the loop, you can no longer use vec because the ownership has been transferred. This is ideal when you don’t need the original collection anymore and want to avoid copying values.

Here vec is still accessible here because only borrowed. Andprintln!("{:?}", vec); works fine, it will print [1, 2, 3, 4]. Use iter() when you just need to read from the collection without modifying it.

With this, you can mutate elements but can’t move or drop them. The Vec is borrowed mutably and remains usable after the loop. Use iter_mut() when you need to modify the elements of a collection in place.
Note: Ownership doesn’t change for primitive types, so it only moves when it is a Vec or struct or any complex object.
In summary, Rust offers a variety of looping mechanisms to suit different needs, while also ensuring that ownership rules are adhered to. By understanding the ownership model, you can safely and effectively manipulate data within your loops. Whether you’re iterating over borrowed values, mutating elements, or taking ownership of them, Rust’s approach ensures memory safety without sacrificing performance. Keep these patterns in mind as you work with Rust’s powerful looping constructs and ownership system.


