| 1 | # What `#[derive(IndexMut)]` generates |
| 2 | |
| 3 | Deriving `IndexMut` only works for a single field of a struct. |
| 4 | Furthermore it requires that the type also implements `Index`, so usually |
| 5 | `Index` should also be derived. |
| 6 | The result is that you will mutably index it's member directly. |
| 7 | |
| 8 | With `#[index_mut]` or `#[index_mut(ignore)]` it's possible to indicate the |
| 9 | field that you want to derive `IndexMut` for. |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | ## Example usage |
| 15 | |
| 16 | ```rust |
| 17 | # use derive_more::{Index, IndexMut}; |
| 18 | # |
| 19 | #[derive(Index, IndexMut)] |
| 20 | struct MyVec(Vec<i32>); |
| 21 | |
| 22 | #[derive(Index, IndexMut)] |
| 23 | struct Numbers { |
| 24 | #[index] |
| 25 | #[index_mut] |
| 26 | numbers: Vec<i32>, |
| 27 | useless: bool, |
| 28 | } |
| 29 | |
| 30 | let mut myvec = MyVec(vec![5, 8]); |
| 31 | myvec[0] = 50; |
| 32 | assert_eq!(50, myvec[0]); |
| 33 | |
| 34 | let mut numbers = Numbers{numbers: vec![100, 200], useless: false}; |
| 35 | numbers[1] = 400; |
| 36 | assert_eq!(400, numbers[1]); |
| 37 | ``` |
| 38 | |
| 39 | |
| 40 | |
| 41 | |
| 42 | ## Regular structs |
| 43 | |
| 44 | When deriving `IndexMut` for a struct: |
| 45 | |
| 46 | ```rust |
| 47 | # use derive_more::{Index, IndexMut}; |
| 48 | # |
| 49 | #[derive(Index, IndexMut)] |
| 50 | struct Numbers { |
| 51 | #[index] |
| 52 | #[index_mut] |
| 53 | numbers: Vec<i32>, |
| 54 | useless: bool, |
| 55 | } |
| 56 | ``` |
| 57 | |
| 58 | Code like this will be generated to implement `IndexMut`: |
| 59 | |
| 60 | ```rust |
| 61 | # use ::core::ops::Index; |
| 62 | # struct Numbers { |
| 63 | # numbers: Vec<i32>, |
| 64 | # useless: bool, |
| 65 | # } |
| 66 | # impl<__IdxT> Index<__IdxT> for Numbers |
| 67 | # where |
| 68 | # Vec<i32>: Index<__IdxT>, |
| 69 | # { |
| 70 | # type Output = <Vec<i32> as Index<__IdxT>>::Output; |
| 71 | # #[inline] |
| 72 | # fn index(&self, idx: __IdxT) -> &Self::Output { |
| 73 | # <Vec<i32> as Index<__IdxT>>::index(&self.numbers, idx) |
| 74 | # } |
| 75 | # } |
| 76 | impl<__IdxT> derive_more::core::ops::IndexMut<__IdxT> for Numbers |
| 77 | where |
| 78 | Vec<i32>: derive_more::core::ops::IndexMut<__IdxT>, |
| 79 | { |
| 80 | #[inline] |
| 81 | fn index_mut(&mut self, idx: __IdxT) -> &mut Self::Output { |
| 82 | <Vec<i32> as derive_more::core::ops::IndexMut<__IdxT>>::index_mut(&mut self.numbers, idx) |
| 83 | } |
| 84 | } |
| 85 | ``` |
| 86 | |
| 87 | |
| 88 | |
| 89 | |
| 90 | ## Enums |
| 91 | |
| 92 | Deriving `IndexMut` is not supported for enums. |