2
2
3
3
## Array expressions
4
4
5
+ > ** <sup >Syntax</sup >**
6
+ > _ ArrayExpression_ :
7
+ >   ;  ;   ;  ; ` [ ` ` ] `
8
+ >   ;  ; | ` [ ` [ _ Expression_ ] ( ` , ` [ _ Expression_ ] )<sup >\* </sup > ` , ` <sup >?</sup > ` ] `
9
+ >   ;  ; | ` [ ` [ _ Expression_ ] ` ; ` [ _ Expression_ ] ` ] `
10
+
5
11
An _ [ array] ( types.html#array-and-slice-types ) expression_ can be written by
6
12
enclosing zero or more comma-separated expressions of uniform type in square
7
13
brackets. This produces and array containing each of these values in the
@@ -20,11 +26,16 @@ greater than 1 then this requires that the type of `a` is
20
26
[1 , 2 , 3 , 4 ];
21
27
[" a" , " b" , " c" , " d" ];
22
28
[0 ; 128 ]; // array with 128 zeros
23
- [0u8 , 0u8 , 0u8 , 0u8 ];
29
+ [0u8 , 0u8 , 0u8 , 0u8 ,];
30
+ [[1 , 0 , 0 ], [0 , 1 , 0 ], [0 , 0 , 1 ]]; // 2D array
24
31
```
25
32
26
33
## Array and slice indexing expressions
27
34
35
+ > ** <sup >Syntax</sup >**
36
+ > _ IndexExpression_ :
37
+ >   ;  ; [ _ Expression_ ] ` [ ` [ _ Expression_ ] ` ] `
38
+
28
39
[ Array and slice] ( types.html#array-and-slice-types ) -typed expressions can be
29
40
indexed by writing a square-bracket-enclosed expression (the index) after them.
30
41
When the array is mutable, the resulting
@@ -50,4 +61,14 @@ let y = (["a", "b"])[n]; // panics
50
61
51
62
let arr = ["a", "b"];
52
63
arr[10]; // panics
64
+
65
+ # let b = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
66
+ b[1][2]; // multidimensional array indexing
53
67
```
68
+
69
+ The array index expression can be implemented for types other than arrays and slices
70
+ by implementing the [ Index] and [ IndexMut] traits.
71
+
72
+ [ Index ] : https://doc.rust-lang.org/std/ops/trait.Index.html
73
+ [ IndexMut ] : https://doc.rust-lang.org/std/ops/trait.IndexMut.html
74
+ [ _Expression_ ] : expressions.html
0 commit comments