
Iterators & Closures
Iterator trait, iterator adapters (map, filter, fold), closure syntax, move closures, Fn traits
1Which trait must a type implement to be usable in a for loop in Rust?
Which trait must a type implement to be usable in a for loop in Rust?
답변
The IntoIterator trait allows a type to be converted into an iterator. The for loop automatically calls into_iter() on the expression. Types like Vec, arrays and ranges implement this trait by default, which allows iterating over them directly with for.
2Which method of the Iterator trait must be implemented?
Which method of the Iterator trait must be implemented?
답변
The next() method is the only required method of the Iterator trait. It returns Option<Self::Item>, either Some(item) if there are remaining elements, or None when iteration is complete. All other methods like map, filter or collect have default implementations based on next().
3What is the difference between iter(), iter_mut() and into_iter() on a Vec<T>?
What is the difference between iter(), iter_mut() and into_iter() on a Vec<T>?
답변
iter() returns an iterator over immutable references (&T), iter_mut() over mutable references (&mut T), and into_iter() consumes the Vec and returns elements by value (T). The choice depends on whether you want to read, modify or take ownership of the elements.
What is a lazy iterator in Rust and why is it important?
What is the correct syntax to define a closure that takes two i32 parameters and returns their sum?
+19 면접 질문