| 1 |
# Using `#[derive(Sum)]` |
| 2 |
|
| 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. |
| 8 |
|
| 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)]`. |
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
## Example usage |
| 17 |
|
| 18 |
```rust |
| 19 |
# use derive_more::{Add, Sum}; |
| 20 |
# |
| 21 |
#[derive(Add, Sum, PartialEq)] |
| 22 |
struct MyInts(i32, i64); |
| 23 |
|
| 24 |
let int_vec = vec![MyInts(2, 3), MyInts(4, 5), MyInts(6, 7)]; |
| 25 |
assert!(MyInts(12, 15) == int_vec.into_iter().sum()) |
| 26 |
``` |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
## Structs |
| 32 |
|
| 33 |
When deriving `Sum` for a struct with two fields its like this: |
| 34 |
|
| 35 |
```rust |
| 36 |
# use derive_more::{Add, Sum}; |
| 37 |
# |
| 38 |
#[derive(Add, Sum)] |
| 39 |
struct MyInts(i32, i64); |
| 40 |
``` |
| 41 |
|
| 42 |
Code like this will be generated for the `Sum` implementation: |
| 43 |
|
| 44 |
```rust |
| 45 |
# struct MyInts(i32, i64); |
| 46 |
# impl ::core::ops::Add for MyInts { |
| 47 |
# type Output = MyInts; |
| 48 |
# #[inline] |
| 49 |
# fn add(self, rhs: MyInts) -> MyInts { |
| 50 |
# MyInts(self.0.add(rhs.0), self.1.add(rhs.1)) |
| 51 |
# } |
| 52 |
# } |
| 53 |
impl ::core::iter::Sum for MyInts { |
| 54 |
#[inline] |
| 55 |
fn sum<I: ::core::iter::Iterator<Item = Self>>(iter: I) -> Self { |
| 56 |
iter.fold( |
| 57 |
MyInts( |
| 58 |
::core::iter::empty::<i32>().sum(), |
| 59 |
::core::iter::empty::<i64>().sum(), |
| 60 |
), |
| 61 |
::core::ops::Add::add, |
| 62 |
) |
| 63 |
} |
| 64 |
} |
| 65 |
``` |
| 66 |
|
| 67 |
The trick here is that we get the identity struct by calling sum on empty |
| 68 |
iterators. |
| 69 |
This way we can get the identity for sum (i.e. `0`) and the identity for product |
| 70 |
(i.e. `1`). |
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
## Enums |
| 76 |
|
| 77 |
Deriving `Sum` for enums is not supported. |