Trait otter::imports::itertools::__std_iter::FromIterator 1.0.0[−][src]
pub trait FromIterator<A> { fn from_iter<T>(iter: T) -> Self
where
T: IntoIterator<Item = A>; }
Expand description
Conversion from an Iterator
.
By implementing FromIterator
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::from_iter()
is rarely called explicitly, and is instead
used through Iterator::collect()
method. See Iterator::collect()
’s
documentation for more examples.
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]);
Using Iterator::collect()
to implicitly use FromIterator
:
let five_fives = std::iter::repeat(5).take(5); let v: Vec<i32> = five_fives.collect(); assert_eq!(v, vec![5, 5, 5, 5, 5]);
Implementing FromIterator
for your type:
use std::iter::FromIterator; // A sample collection, that's just a wrapper over Vec<T> #[derive(Debug)] struct MyCollection(Vec<i32>); // 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<i32> for MyCollection { fn from_iter<I: IntoIterator<Item=i32>>(iter: I) -> Self { 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.0, vec![0, 1, 2, 3, 4]); // collect works too! let iter = (0..5).into_iter(); let c: MyCollection = iter.collect(); assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
Required methods
fn from_iter<T>(iter: T) -> Self where
T: IntoIterator<Item = A>,
[src]
fn from_iter<T>(iter: T) -> Self where
T: IntoIterator<Item = A>,
[src]Creates a value from an iterator.
See the module-level documentation for more.
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]);
Implementations on Foreign Types
Collapses all unit items from an iterator into one.
This is more useful when combined with higher-level abstractions, like
collecting to a Result<(), E>
where you only care about errors:
use std::io::*; let data = vec![1, 2, 3, 4, 5]; let res: Result<()> = data.iter() .map(|x| writeln!(stdout(), "{}", x)) .collect(); assert!(res.is_ok());
Takes each element in the Iterator
: if it is None
,
no further elements are taken, and the None
is
returned. Should no None
occur, a container with the
values of each Option
is returned.
Examples
Here is an example which increments every integer in a vector.
We use the checked variant of add
that returns None
when the
calculation would result in an overflow.
let items = vec![0_u16, 1, 2]; let res: Option<Vec<u16>> = items .iter() .map(|x| x.checked_add(1)) .collect(); assert_eq!(res, Some(vec![1, 2, 3]));
As you can see, this will return the expected, valid items.
Here is another example that tries to subtract one from another list of integers, this time checking for underflow:
let items = vec![2_u16, 1, 0]; let res: Option<Vec<u16>> = items .iter() .map(|x| x.checked_sub(1)) .collect(); assert_eq!(res, None);
Since the last element is zero, it would underflow. Thus, the resulting
value is None
.
Here is a variation on the previous example, showing that no
further elements are taken from iter
after the first None
.
let items = vec![3_u16, 2, 1, 10]; let mut shared = 0; let res: Option<Vec<u16>> = items .iter() .map(|x| { shared += x; x.checked_sub(2) }) .collect(); assert_eq!(res, None); assert_eq!(shared, 6);
Since the third element caused an underflow, no further elements were taken,
so the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
Takes each element in the Iterator
: if it is an Err
, no further
elements are taken, and the Err
is returned. Should no Err
occur, a
container with the values of each Result
is returned.
Here is an example which increments every integer in a vector, checking for overflow:
let v = vec![1, 2]; let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| x.checked_add(1).ok_or("Overflow!") ).collect(); assert_eq!(res, Ok(vec![2, 3]));
Here is another example that tries to subtract one from another list of integers, this time checking for underflow:
let v = vec![1, 2, 0]; let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| x.checked_sub(1).ok_or("Underflow!") ).collect(); assert_eq!(res, Err("Underflow!"));
Here is a variation on the previous example, showing that no
further elements are taken from iter
after the first Err
.
let v = vec![3, 2, 1, 10]; let mut shared = 0; let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| { shared += x; x.checked_sub(2).ok_or("Underflow!") }).collect(); assert_eq!(res, Err("Underflow!")); assert_eq!(shared, 6);
Since the third element caused an underflow, no further elements were taken,
so the final value of shared
is 6 (= 3 + 2 + 1
), not 16.
Takes each element in the Iterator
and collects it into an Rc<[T]>
.
Performance characteristics
The general case
In the general case, collecting into Rc<[T]>
is done by first
collecting into a Vec<T>
. That is, when writing the following:
let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
this behaves as if we wrote:
let evens: Rc<[u8]> = (0..10).filter(|&x| x % 2 == 0) .collect::<Vec<_>>() // The first set of allocations happens here. .into(); // A second allocation for `Rc<[T]>` happens here.
This will allocate as many times as needed for constructing the Vec<T>
and then it will allocate once for turning the Vec<T>
into the Rc<[T]>
.
Iterators of known length
When your Iterator
implements TrustedLen
and is of an exact size,
a single allocation will be made for the Rc<[T]>
. For example:
let evens: Rc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
impl<T, N> FromIterator<T> for GenericArray<T, N> where
N: ArrayLength<T>,
impl<T, N> FromIterator<T> for GenericArray<T, N> where
N: ArrayLength<T>,
pub fn from_iter<I>(iter: I) -> GenericArray<T, N> where
I: IntoIterator<Item = T>,
impl FromIterator<Op> for Op
impl FromIterator<Op> for Op
pub fn from_iter<T>(iterator: T) -> Op where
T: IntoIterator<Item = Op>,
impl<T> FromIterator<(usize, T)> for Slab<T>
impl<T> FromIterator<(usize, T)> for Slab<T>
Create a slab from an iterator of key-value pairs.
If the iterator produces duplicate keys, the previous value is replaced with the later one.
The keys does not need to be sorted beforehand, and this function always
takes O(n) time.
Note that the returned slab will use space proportional to the largest key,
so don’t use Slab
with untrusted keys.
Examples
let vec = vec![(2,'a'), (6,'b'), (7,'c')]; let slab = vec.into_iter().collect::<Slab<char>>(); assert_eq!(slab.len(), 3); assert!(slab.capacity() >= 8); assert_eq!(slab[2], 'a');
With duplicate and unsorted keys:
let vec = vec![(20,'a'), (10,'b'), (11,'c'), (10,'d')]; let slab = vec.into_iter().collect::<Slab<char>>(); assert_eq!(slab.len(), 3); assert_eq!(slab[10], 'd');
pub fn from_iter<I>(iterable: I) -> Slab<T> where
I: IntoIterator<Item = (usize, T)>,
impl FromIterator<EventMask> for EventMask
impl FromIterator<EventMask> for EventMask
pub fn from_iter<T>(iterator: T) -> EventMask where
T: IntoIterator<Item = EventMask>,
impl FromIterator<WatchMask> for WatchMask
impl FromIterator<WatchMask> for WatchMask
pub fn from_iter<T>(iterator: T) -> WatchMask where
T: IntoIterator<Item = WatchMask>,
pub fn from_iter<T>(iter: T) -> Box<IndexSlice<I, [A]>, Global>ⓘ where
T: IntoIterator<Item = A>,
[src]pub fn from_iter<T>(iterator: T) -> InterfaceFlags where
T: IntoIterator<Item = InterfaceFlags>,
[src]pub fn from_iter<T>(iterator: T) -> FallocateFlags where
T: IntoIterator<Item = FallocateFlags>,
[src]pub fn from_iter<T>(iterator: T) -> QuotaValidFlags where
T: IntoIterator<Item = QuotaValidFlags>,
[src]pub fn from_iter<T>(iterator: T) -> ModuleInitFlags where
T: IntoIterator<Item = ModuleInitFlags>,
[src]pub fn from_iter<T>(iterator: T) -> TimerSetTimeFlags where
T: IntoIterator<Item = TimerSetTimeFlags>,
[src]pub fn from_iter<T>(iterator: T) -> AddWatchFlags where
T: IntoIterator<Item = AddWatchFlags>,
[src]pub fn from_iter<T>(iterator: T) -> MlockAllFlags where
T: IntoIterator<Item = MlockAllFlags>,
[src]pub fn from_iter<T>(iterator: T) -> MemFdCreateFlag where
T: IntoIterator<Item = MemFdCreateFlag>,
[src]pub fn from_iter<T>(iterator: T) -> DeleteModuleFlags where
T: IntoIterator<Item = DeleteModuleFlags>,
[src]pub fn from_iter<T>(iterator: T) -> EpollCreateFlags where
T: IntoIterator<Item = EpollCreateFlags>,
[src]impl<A> FromIterator<<A as Array>::Item> for SmallVec<A> where
A: Array,
impl<A> FromIterator<<A as Array>::Item> for SmallVec<A> where
A: Array,
pub fn from_iter<I>(iterable: I) -> SmallVec<A> where
I: IntoIterator<Item = <A as Array>::Item>,
impl<A> FromIterator<<A as Array>::Item> for ArrayVec<A> where
A: Array,
impl<A> FromIterator<<A as Array>::Item> for ArrayVec<A> where
A: Array,
#[must_use]pub fn from_iter<T>(iter: T) -> ArrayVec<A> where
T: IntoIterator<Item = <A as Array>::Item>,
impl<A> FromIterator<<A as Array>::Item> for TinyVec<A> where
A: Array,
impl<A> FromIterator<<A as Array>::Item> for TinyVec<A> where
A: Array,
#[must_use]pub fn from_iter<T>(iter: T) -> TinyVec<A> where
T: IntoIterator<Item = <A as Array>::Item>,
impl FromIterator<Transformations> for Transformations
impl FromIterator<Transformations> for Transformations
pub fn from_iter<T>(iterator: T) -> Transformations where
T: IntoIterator<Item = Transformations>,
impl FromIterator<FileType> for FileType
impl FromIterator<FileType> for FileType
pub fn from_iter<T>(iterator: T) -> FileType where
T: IntoIterator<Item = FileType>,
impl<'a> FromIterator<&'a BStr> for BString
impl<'a> FromIterator<&'a BStr> for BString
pub fn from_iter<T>(iter: T) -> BString where
T: IntoIterator<Item = &'a BStr>,
impl<'a> FromIterator<&'a [u8]> for BString
impl<'a> FromIterator<&'a [u8]> for BString
pub fn from_iter<T>(iter: T) -> BString where
T: IntoIterator<Item = &'a [u8]>,
impl<'a> FromIterator<&'a str> for BString
impl<'a> FromIterator<&'a str> for BString
pub fn from_iter<T>(iter: T) -> BString where
T: IntoIterator<Item = &'a str>,
impl FromIterator<char> for BString
impl FromIterator<char> for BString
pub fn from_iter<T>(iter: T) -> BString where
T: IntoIterator<Item = char>,
impl FromIterator<BString> for BString
impl FromIterator<BString> for BString
pub fn from_iter<T>(iter: T) -> BString where
T: IntoIterator<Item = BString>,
impl FromIterator<u8> for BString
impl FromIterator<u8> for BString
pub fn from_iter<T>(iter: T) -> BString where
T: IntoIterator<Item = u8>,
Implementors
impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S> where
K: Eq + Hash,
S: BuildHasher + Default,
[src]
impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S> where
K: Eq + Hash,
S: BuildHasher + Default,
[src]impl<K, V, S> FromIterator<(K, V)> for SparseSecondaryMap<K, V, S> where
K: Key,
S: BuildHasher + Default,
[src]
impl<K, V, S> FromIterator<(K, V)> for SparseSecondaryMap<K, V, S> where
K: Key,
S: BuildHasher + Default,
[src]pub fn from_iter<I>(iter: I) -> SparseSecondaryMap<K, V, S> where
I: IntoIterator<Item = (K, V)>,
[src]Convert an iteratable type to a Value
Examples
use serde_json::Value; let v = std::iter::repeat(42).take(5); let x: Value = v.collect();
use serde_json::Value; let v: Vec<_> = vec!["lorem", "ipsum", "dolor"]; let x: Value = v.into_iter().collect();
use std::iter::FromIterator; use serde_json::Value; let x: Value = Value::from_iter(vec!["lorem", "ipsum", "dolor"]);
Takes each element in the Iterator
and collects it into an Arc<[T]>
.
Performance characteristics
The general case
In the general case, collecting into Arc<[T]>
is done by first
collecting into a Vec<T>
. That is, when writing the following:
let evens: Arc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect();
this behaves as if we wrote:
let evens: Arc<[u8]> = (0..10).filter(|&x| x % 2 == 0) .collect::<Vec<_>>() // The first set of allocations happens here. .into(); // A second allocation for `Arc<[T]>` happens here.
This will allocate as many times as needed for constructing the Vec<T>
and then it will allocate once for turning the Vec<T>
into the Arc<[T]>
.
Iterators of known length
When your Iterator
implements TrustedLen
and is of an exact size,
a single allocation will be made for the Arc<[T]>
. For example:
let evens: Arc<[u8]> = (0..10).collect(); // Just a single allocation happens here.
Create an ArrayVec
from an iterator.
Panics if the number of elements in the iterator exceeds the arrayvec’s capacity.