Trait core::iter::Sum 1.12.0[−][src]
Trait to represent types that can be created by summing up an iterator.
This trait is used to implement the sum()
method on iterators. Types which
implement the trait can be generated by the sum()
method. Like
FromIterator
this trait should rarely be called directly and instead
interacted with through Iterator::sum()
.
Required methods
fn sum<I: Iterator<Item = A>>(iter: I) -> Self
[src]
Method which takes an iterator and generates Self
from the elements by
“summing up” the items.
Implementors
impl<T, U> Sum<Option<U>> for Option<T> where
T: Sum<U>,
1.37.0[src]
impl<T, U> Sum<Option<U>> for Option<T> where
T: Sum<U>,
1.37.0[src]fn sum<I>(iter: I) -> Option<T> where
I: Iterator<Item = Option<U>>,
[src]
I: Iterator<Item = Option<U>>,
Takes each element in the Iterator
: if it is a None
, no further
elements are taken, and the None
is returned. Should no None
occur, the sum of all elements is returned.
Examples
This sums up the position of the character ‘a’ in a vector of strings,
if a word did not have the character ‘a’ the operation returns None
:
let words = vec!["have", "a", "great", "day"]; let total: Option<usize> = words.iter().map(|w| w.find('a')).sum(); assert_eq!(total, Some(5));Run
impl<T, U, E> Sum<Result<U, E>> for Result<T, E> where
T: Sum<U>,
1.16.0[src]
impl<T, U, E> Sum<Result<U, E>> for Result<T, E> where
T: Sum<U>,
1.16.0[src]fn sum<I>(iter: I) -> Result<T, E> where
I: Iterator<Item = Result<U, E>>,
[src]
I: Iterator<Item = Result<U, E>>,
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, the sum of all elements is returned.
Examples
This sums up every integer in a vector, rejecting the sum if a negative element is encountered:
let v = vec![1, 2]; let res: Result<i32, &'static str> = v.iter().map(|&x: &i32| if x < 0 { Err("Negative element found") } else { Ok(x) } ).sum(); assert_eq!(res, Ok(3));Run