Sum And Product Trait Implementations
Implement Sum and Product for a custom type so iterator collect and fold adapters reuse the standard numeric reduction API.
Code
use std::iter::{Product, Sum};
#[derive(Debug, Clone, Copy, PartialEq)]
struct Mod10(u32);
impl Mod10 {
fn new(value: u32) -> Self {
Mod10(value % 10)
}
}
// Sum:折叠加法并保持模 10 封闭
impl Sum for Mod10 {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
Mod10(iter.fold(0, |acc, item| (acc + item.0) % 10))
}
}
// Product:折叠乘法,单位元是 1 而不是 0
impl Product for Mod10 {
fn product<I: Iterator<Item = Self>>(iter: I) -> Self {
Mod10(iter.fold(1, |acc, item| (acc * item.0) % 10))
}
}
fn main() {
let digits = [Mod10::new(3), Mod10::new(4), Mod10::new(5)];
// .sum() 与 .product() 直接复用 trait 实现
let sum: Mod10 = digits.iter().copied().sum();
let product: Mod10 = digits.iter().copied().product();
println!("sum={} product={}", sum.0, product.0);
// 空迭代器分别得到加法与乘法单位元
let empty: [Mod10; 0] = [];
let zero: Mod10 = empty.iter().copied().sum();
let one: Mod10 = empty.iter().copied().product();
println!("identity: sum={} product={}", zero.0, one.0);
}How it works
Sum And Product Trait Implementations keeps everything in the functions new, sum, product and main.
Applying it
The primary signature is fn new(value: u32) -> Self
Each run prints the 2 labeled blocks sum=, identity: sum= in source order.
The entry point wires new, sum and product together — run it once and the whole demo flows.
Statements that matter
let sum: Mod10 = digits.iter().copied().sum();
let zero: Mod10 = empty.iter().copied().sum();
fn product<I: Iterator<Item = Self>>(iter: I) -> Self {
Mod10(iter.fold(1, |acc, item| (acc * item.0) % 10))
}
Interactive Tools for This Topic
FAQ
- What does Sum And Product Trait Implementations print when run?
- Invoke the file as-is — the `sum=`, `identity: sum=` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.