What is the difference between iter and into_iter in Rust?
What is the difference between iter and into_iter in Rust?
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()
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()
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
Ownership Transfer:
iter()
: Borrows elements immutably, does not consume the collection.into_iter()
: Takes ownership of elements, consumes the collection.Mutability:
iter()
: Provides immutable references to the elements.into_iter()
: Provides owned values, allowing for transformations that require ownership.Post-Iteration Use:
iter()
: The original collection remains usable after iteration.into_iter()
: The original collection is no longer usable after iteration.iter()
when you ne...middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào