What is the difference between iter and into_iter?

ghz 21days ago ⋅ 27 views

In Rust, iter and into_iter are two methods that can be used to iterate over a collection, but they have key differences regarding ownership and the type of elements they yield. Here's a breakdown of their differences:

1. iter Method

  • Type of Iterator: It creates an immutable reference iterator over the collection.
  • Ownership: iter does not take ownership of the collection. It borrows the collection and gives you an iterator that yields references to the items in the collection (&T).
  • Use Case: You use iter when you want to iterate over a collection but don't want to move or take ownership of the items. The items remain in the collection after the iteration.
let vec = vec![1, 2, 3, 4];
for item in vec.iter() {
    println!("{}", item); // `item` is a reference to an element, i.e., `&i32`
}
  • Example:
    let vec = vec![1, 2, 3];
    let iter = vec.iter();
    for item in iter {
        println!("{}", item); // item is a reference (&i32)
    }
    // vec is still available here
    

2. into_iter Method

  • Type of Iterator: It creates an owned iterator that consumes the collection.
  • Ownership: into_iter takes ownership of the collection, meaning the collection is moved and no longer available after calling into_iter. The iterator yields owned values instead of references (T).
  • Use Case: You use into_iter when you want to consume the collection and take ownership of its items, i.e., you no longer need the original collection after the iteration.
let vec = vec![1, 2, 3, 4];
for item in vec.into_iter() {
    println!("{}", item); // `item` is an owned value (i32)
}
// vec is no longer available here
  • Example:
    let vec = vec![1, 2, 3];
    let into_iter = vec.into_iter();
    for item in into_iter {
        println!("{}", item); // item is an owned value (i32)
    }
    // vec is no longer available here
    

Key Differences:

  • iter: Yields immutable references (&T), does not take ownership of the collection, and the collection remains usable after iteration.
  • into_iter: Yields owned values (T), takes ownership of the collection, and the collection is no longer available after iteration.

Summary:

  • Use iter when you want to borrow elements from the collection without consuming it.
  • Use into_iter when you want to consume the collection and take ownership of its elements.