Debian Codegraph @

debian/missing-sources/derive_more-impl/doc/sum.md

raw symbols SCIP
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 # use ::core::ops::Add;
46 # struct MyInts(i32, i64);
47 # impl Add for MyInts {
48 # type Output = MyInts;
49 # #[inline]
50 # fn add(self, rhs: MyInts) -> MyInts {
51 # MyInts(self.0.add(rhs.0), self.1.add(rhs.1))
52 # }
53 # }
54 impl derive_more::core::iter::Sum for MyInts {
55 #[inline]
56 fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
57 iter.fold(
58 MyInts(
59 derive_more::core::iter::empty::<i32>().sum(),
60 derive_more::core::iter::empty::<i64>().sum(),
61 ),
62 derive_more::core::ops::Add::add,
63 )
64 }
65 }
66 ```
67
68 The trick here is that we get the identity struct by calling sum on empty
69 iterators.
70 This way we can get the identity for sum (i.e. `0`) and the identity for product
71 (i.e. `1`).
72
73
74
75
76 ## Enums
77
78 Deriving `Sum` for enums is not supported.