trait
Sum — result type for iterator totals
Specify how a type is produced from a sequence of summands. Iterator::sum delegates to the selected output type implementation. A custom type may implement Sum for another item type. Expected stdout (not executed): 10 Common mistake: Assuming any type implementing Add automatically implements Sum.
Formal Syntax & Structure
rust syntaxrust
pub trait Sum<A = Self>: Sized { fn sum<I>(iter: I) -> Self where I: Iterator<Item = A>; }Working Example
Example Snippetrust
fn main() { use std::iter::Sum; #[derive(Debug)] struct Total(u32); impl Sum<u32> for Total { fn sum<I: Iterator<Item = u32>>(iter: I) -> Self { Total(iter.sum()) } } let total: Total = [2, 3, 5].into_iter().sum(); println!("{}", total.0);}