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