summaryrefslogtreecommitdiffstats
path: root/third_party/rust/derive_more-impl/doc/index_mut.md
blob: ff2347796e57adfa6a243dfcca3122e2abdeeb42 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# What `#[derive(IndexMut)]` generates

Deriving `IndexMut` only works for a single field of a struct.
Furthermore it requires that the type also implements `Index`, so usually
`Index` should also be derived.
The result is that you will mutably index it's member directly.

With `#[index_mut]` or `#[index_mut(ignore)]` it's possible to indicate the
field that you want to derive `IndexMut` for.




## Example usage

```rust
# use derive_more::{Index, IndexMut};
#
#[derive(Index, IndexMut)]
struct MyVec(Vec<i32>);

#[derive(Index, IndexMut)]
struct Numbers {
    #[index]
    #[index_mut]
    numbers: Vec<i32>,
    useless: bool,
}

let mut myvec = MyVec(vec![5, 8]);
myvec[0] = 50;
assert_eq!(50, myvec[0]);

let mut numbers = Numbers{numbers: vec![100, 200], useless: false};
numbers[1] = 400;
assert_eq!(400, numbers[1]);
```




## Regular structs

When deriving `IndexMut` for a struct:

```rust
# use derive_more::{Index, IndexMut};
#
#[derive(Index, IndexMut)]
struct Numbers {
    #[index]
    #[index_mut]
    numbers: Vec<i32>,
    useless: bool,
}
```

Code like this will be generated to implement `IndexMut`:

```rust
# struct Numbers {
#     numbers: Vec<i32>,
#     useless: bool,
# }
# impl<__IdxT> ::core::ops::Index<__IdxT> for Numbers
# where
#     Vec<i32>: ::core::ops::Index<__IdxT>,
# {
#     type Output = <Vec<i32> as ::core::ops::Index<__IdxT>>::Output;
#     #[inline]
#     fn index(&self, idx: __IdxT) -> &Self::Output {
#         <Vec<i32> as ::core::ops::Index<__IdxT>>::index(&self.numbers, idx)
#     }
# }
impl<__IdxT> ::core::ops::IndexMut<__IdxT> for Numbers
where
    Vec<i32>: ::core::ops::IndexMut<__IdxT>,
{
    #[inline]
    fn index_mut(&mut self, idx: __IdxT) -> &mut Self::Output {
        <Vec<i32> as ::core::ops::IndexMut<__IdxT>>::index_mut(&mut self.numbers, idx)
    }
}
```




## Enums

Deriving `IndexMut` is not supported for enums.