pub trait IntoIterator {
type Item;
type IntoIter: Iterator<Item = Self::Item>;
// Required method
fn into_iter(self) -> Self::IntoIter;
}
Expand description
Conversion into an Iterator
.
By implementing IntoIterator
for a type, you define how it will be converted to an iterator. This is common for types which describe a collection of some kind.
One benefit of implementing IntoIterator
is that your type will work with Rustâs for
loop syntax.
See also: FromIterator
.
Basic usage:
let v = [1, 2, 3];
let mut iter = v.into_iter();
assert_eq!(Some(1), iter.next());
assert_eq!(Some(2), iter.next());
assert_eq!(Some(3), iter.next());
assert_eq!(None, iter.next());
Implementing IntoIterator
for your type:
#[derive(Debug)]
struct MyCollection(Vec<i32>);
impl MyCollection {
fn new() -> MyCollection {
MyCollection(Vec::new())
}
fn add(&mut self, elem: i32) {
self.0.push(elem);
}
}
impl IntoIterator for MyCollection {
type Item = i32;
type IntoIter = std::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
let mut c = MyCollection::new();
c.add(0);
c.add(1);
c.add(2);
for (i, n) in c.into_iter().enumerate() {
assert_eq!(i as i32, n);
}
It is common to use IntoIterator
as a trait bound. This allows the input collection type to change, so long as it is still an iterator. Additional bounds can be specified by restricting on Item
:
fn collect_as_strings<T>(collection: T) -> Vec<String>
where
T: IntoIterator,
T::Item: std::fmt::Debug,
{
collection
.into_iter()
.map(|item| format!("{item:?}"))
.collect()
}
1.0.0 · Source
The type of the elements being iterated over.
1.0.0 · SourceWhich kind of iterator are we turning this into?
1.0.0 · SourceCreates an iterator from a value.
See the module-level documentation for more.
§Exampleslet v = [1, 2, 3];
let mut iter = v.into_iter();
assert_eq!(Some(1), iter.next());
assert_eq!(Some(2), iter.next());
assert_eq!(Some(3), iter.next());
assert_eq!(None, iter.next());
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4