摘要:广东# 1.0.0[−][src]Trait std:: 1.0.0[−][src]Trait std::iter::FromIteratorConversion from anIterator.By implementingFromIterator for a type, you define how it will becreated from an iterator. This is com...
广东# 1.0.0[−][src]Trait std::
1.0.0[−][src]Trait std::
iter::FromIterator
Conversion from anIterator.
By implementingFromIterator for a type, you define how it will be
created from an iterator. This is common for types which describe a
collection of some kind.
FromIterator's full signature is:
pub trait FromIterator {
fn from_iter
where
T: IntoIterator
}Run
It is rarely necessary to implement this trait directly, as implementing theIterator trait for a type will provide a default implementation of
FromIterator (see the "Implementors" section below).
See also:IntoIterator.
Examples
Basic usage:
use std::iter::FromIterator;
let five_fives = std::iter::repeat(5).take(5);
let v = Vec::from_iter(five_fives);
assert_eq!(v, vec![5, 5, 5, 5, 5]);Run
Usingcollect to implicitly use FromIterator:
let five_fives = std::iter::repeat(5).take(5);
let v: Vec
assert_eq!(v, vec![5, 5, 5, 5, 5]);Run
ImplementingFromIterator for your type:
use std::iter::FromIterator;
// A sample collection, that's just a wrapper over Vec
[derive(Debug)]
struct MyCollection(Vec
// Let's give it some methods so we can create one and add things to it
impl MyCollection {
fn new() -> MyCollection {
MyCollection(Vec::new())
}
fn add(&mut self, elem: i32) {
self.0.push(elem);
}
}
// and we'll implement FromIterator
impl FromIterator
fn from_iter
let mut c = MyCollection::new();
for i in iter {
c.add(i);
}
c
}
}
// Now we can make a new iterator...
let iter = (0..5).into_iter();
// ... and make a MyCollection out of it
let c = MyCollection::from_iter(iter);
assert_eq!(c.