Course contentsShow
← Rust
Lesson 96 of 1,9102. The Ownership ModelFree lesson

Ownership Transfer during Loop Iteration

Navigate the movement of data values when consuming collection elements in loops.

In this lesson, you will learn how iterating over a collection can transfer ownership of its elements, effectively "consuming" the container.

Moving Through a Collection

When you have a collection of items—like a Vec containing heap-allocated data—Rust needs to decide what happens to those items when you loop over them. If you iterate over the collection directly using a for loop, you are telling Rust to take ownership of each element one by one.

The "Consumption" Loop

Imagine you have a Vec of String objects. Because a String owns data on the heap, it cannot simply be copied. When you write a loop like for item in my_vec, Rust moves the ownership of each string out of the vector and into the item variable for that iteration.

let my_vec = vec![String::from("Rust"), String::from("Ownership")];

for item in my_vec {
    // Ownership of the String moved from the vec to 'item' here.
    println!("{}", item);
} // 'item' goes out of scope here and is dropped.

// If you tried to use 'my_vec' here, the compiler would stop you!
// The vector is now effectively empty or invalidated because 
// we moved all its contents out during the loop.

Why does this happen?

The for loop syntax relies on a trait called IntoIterator. When you pass my_vec directly into the loop, it calls into_iter(), which consumes the original collection. Each iteration takes a value out of the collection's memory, leaving the original container in a state where it no longer owns those elements.

If you don't want to move the values (and lose your collection), you must iterate by reference instead. By using for item in &my_vec, you borrow each element rather than taking ownership of it. This allows the collection to stay intact, and your loop simply "looks" at the data without destroying it.

Understanding this distinction is vital for preventing "use of moved value" errors. When you loop, ask yourself: "Do I need this collection to exist after the loop is finished?" If the answer is yes, ensure you are borrowing the elements, not consuming them.

Key Takeaway: Iterating directly over a collection moves its elements into the loop scope, consuming the collection; use references (&collection) if you need the collection to persist after the loop.