1 # Using `#[derive(Sum)]`
3 The derived `Sum` implementation will allow an iterator of your type to be
4 summed together into a new instance of the type with all the fields added
5 together. Apart from the original types requiring an implementation of `Sum`, it
6 is also required that your type to implements `Add`. So normally you want to
7 derive that one as well.
9 All this is also true for the `Product`, except that then all the fields are
10 multiplied and an implementation of `Mul` is required. This is usually the
11 easiest to implement by adding `#[derive(MulSelf)]`.
19 # use derive_more::{Add, Sum};
21 #[derive(Add, Sum, PartialEq)]
22 struct MyInts(i32, i64);
24 let int_vec = vec![MyInts(2, 3), MyInts(4, 5), MyInts(6, 7)];
25 assert!(MyInts(12, 15) == int_vec.into_iter().sum())
33 When deriving `Sum` for a struct with two fields its like this:
36 # use derive_more::{Add, Sum};
39 struct MyInts(i32, i64);
42 Code like this will be generated for the `Sum` implementation:
45 # struct MyInts(i32, i64);
46 # impl ::core::ops::Add for MyInts {
47 # type Output = MyInts;
49 # fn add(self, rhs: MyInts) -> MyInts {
50 # MyInts(self.0.add(rhs.0), self.1.add(rhs.1))
53 impl ::core::iter::Sum for MyInts {
55 fn sum<I: ::core::iter::Iterator<Item = Self>>(iter: I) -> Self {
58 ::core::iter::empty::<i32>().sum(),
59 ::core::iter::empty::<i64>().sum(),
61 ::core::ops::Add::add,
67 The trick here is that we get the identity struct by calling sum on empty
69 This way we can get the identity for sum (i.e. `0`) and the identity for product
77 Deriving `Sum` for enums is not supported.