Câu hỏi phỏng vấn Rust
Câu hỏi

What is the difference between iter and into_iter in Rust?

Câu trả lời

In Rust, iter and into_iter are methods used to create iterators from collections, but they differ significantly in how they handle ownership and mutability.

iter()

  • Purpose: Creates an iterator that borrows each element of the collection immutably.
  • Ownership: The original collection is not consumed, meaning it remains available for use after the iteration.
  • Usage: Suitable when you need to read elements without modifying the collection.
  • Example:
    rust Copy
    let vec = vec![1, 2, 3];
    let mut iter = vec.iter();
    assert_eq!(iter.next(), Some(&1));
    assert_eq!(iter.next(), Some(&2));
    assert_eq!(iter.next(), Some(&3));
    assert_eq!(iter.next(), None);
    // vec is still usable here

into_iter()

  • Purpose: Creates an iterator that takes ownership of the collection, consuming it.
  • Ownership: The original collection is consumed, meaning it cannot be used after the iteration.
  • Usage: Suitable when you need to take ownership of the elements, often for transforming or moving them.
  • Example:
    rust Copy
    let vec = vec![1, 2, 3];
    let mut iter = vec.into_iter();
    assert_eq!(iter.next(), Some(1));
    assert_eq!(iter.next(), Some(2));
    assert_eq!(iter.next(), Some(3));
    assert_eq!(iter.next(), None);
    // vec is no longer usable here

Key Differences

  1. Ownership Transfer:

    • iter(): Borrows elements immutably, does not consume the collection.
    • into_iter(): Takes ownership of elements, consumes the collection.
  2. Mutability:

    • iter(): Provides immutable references to the elements.
    • into_iter(): Provides owned values, allowing for transformations that require ownership.
  3. Post-Iteration Use:

    • iter(): The original collection remains usable after iteration.
    • into_iter(): The original collection is no longer usable after iteration.

Practical Implications

  • Use iter() when you ne...
middle

middle

Gợi ý câu hỏi phỏng vấn

middle

Compare Rc vs Arc in Rust

junior

What happens when you pass a String to a function in Rust?

senior

Explain what is Send and Sync in Rust and when do you need them?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào