summaryrefslogtreecommitdiffstats
path: root/third_party/rust/derive_more-impl/doc/index.md
blob: c45fb46df5ec23ad0e581ab354b835e5bc87dada (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
# What `#[derive(Index)]` generates

Deriving `Index` only works for a single field of a struct.
The result is that you will index it's member directly.

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




## Example usage

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

// You can specify the field you want to derive Index for
#[derive(Index)]
struct Numbers {
    #[index]
    numbers: Vec<i32>,
    useless: bool,
}

assert_eq!(5, MyVec(vec![5, 8])[0]);
assert_eq!(200, Numbers { numbers: vec![100, 200], useless: false }[1]);
```




## Structs

When deriving `Index` for a struct:

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

Code like this will be generated:

```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)
    }
}
```




## Enums

Deriving `Index` is not supported for enums.