no bug - Correct some typos in the comments. a=typo-fix
[gecko.git] / third_party / rust / derive_more-impl / doc / sum.md
blobffb5ea6be206a2fca32f065b6bde16a1280cece8
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)]`.
16 ## Example usage
18 ```rust
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())
26 ```
31 ## Structs
33 When deriving `Sum` for a struct with two fields its like this:
35 ```rust
36 # use derive_more::{Add, Sum};
38 #[derive(Add, Sum)]
39 struct MyInts(i32, i64);
40 ```
42 Code like this will be generated for the `Sum` implementation:
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     }
65 ```
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`).
75 ## Enums
77 Deriving `Sum` for enums is not supported.