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:
    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:
    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

expert

Explain the use of async / .await in Rust

junior

What is the Option type in Rust, and why is it useful?

expert

What are the specific conditions for a closure to implement the Fn , FnMut and FnOnce traits?

Bình luận

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

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