pub trait Sum<A = Self>: Sized {
// Required method
fn sum<'a, S>(stream: S) -> Pin<Box<dyn Future<Output = Self> + 'a>>
where S: Stream<Item = A> + 'a;
}
unstable
only.Expand description
Trait to represent types that can be created by summing up a stream.
This trait is used to implement the sum
method on streams. Types which
implement the trait can be generated by the sum
method. Like
FromStream
this trait should rarely be called directly and instead
interacted with through Stream::sum
.
Required Methods§
Object Safety§
Implementations on Foreign Types§
source§impl<T, U> Sum<Option<U>> for Option<T>where
T: Sum<U>,
impl<T, U> Sum<Option<U>> for Option<T>where
T: Sum<U>,
source§fn sum<'a, S>(stream: S) -> Pin<Box<dyn Future<Output = Option<T>> + 'a>>
fn sum<'a, S>(stream: S) -> Pin<Box<dyn Future<Output = Option<T>> + 'a>>
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
:
use async_std::prelude::*;
use async_std::stream;
let words = stream::from_iter(vec!["have", "a", "great", "day"]);
let total: Option<usize> = words.map(|w| w.find('a')).sum().await;
assert_eq!(total, Some(5));
source§impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where
T: Sum<U>,
impl<T, U, E> Sum<Result<U, E>> for Result<T, E>where
T: Sum<U>,
source§fn sum<'a, S>(stream: S) -> Pin<Box<dyn Future<Output = Result<T, E>> + 'a>>
fn sum<'a, S>(stream: S) -> Pin<Box<dyn Future<Output = Result<T, E>> + 'a>>
Takes each element in the Stream
: 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:
use async_std::prelude::*;
use async_std::stream;
let v = stream::from_iter(vec![1, 2]);
let res: Result<i32, &'static str> = v.map(|x|
if x < 0 {
Err("Negative element found")
} else {
Ok(x)
}).sum().await;
assert_eq!(res, Ok(3));