| 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 |
# struct Numbers { |
| 62 |
# numbers: Vec<i32>, |
| 63 |
# useless: bool, |
| 64 |
# } |
| 65 |
# impl<__IdxT> ::core::ops::Index<__IdxT> for Numbers |
| 66 |
# where |
| 67 |
# Vec<i32>: ::core::ops::Index<__IdxT>, |
| 68 |
# { |
| 69 |
# type Output = <Vec<i32> as ::core::ops::Index<__IdxT>>::Output; |
| 70 |
# #[inline] |
| 71 |
# fn index(&self, idx: __IdxT) -> &Self::Output { |
| 72 |
# <Vec<i32> as ::core::ops::Index<__IdxT>>::index(&self.numbers, idx) |
| 73 |
# } |
| 74 |
# } |
| 75 |
impl<__IdxT> ::core::ops::IndexMut<__IdxT> for Numbers |
| 76 |
where |
| 77 |
Vec<i32>: ::core::ops::IndexMut<__IdxT>, |
| 78 |
{ |
| 79 |
#[inline] |
| 80 |
fn index_mut(&mut self, idx: __IdxT) -> &mut Self::Output { |
| 81 |
<Vec<i32> as ::core::ops::IndexMut<__IdxT>>::index_mut(&mut self.numbers, idx) |
| 82 |
} |
| 83 |
} |
| 84 |
``` |
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
## Enums |
| 90 |
|
| 91 |
Deriving `IndexMut` is not supported for enums. |