Skip to content

Commit c75dbea

Browse files
committed
Array and indexing grammar
1 parent 7bfc70e commit c75dbea

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

src/expressions/array-expr.md

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,12 @@
22

33
## Array expressions
44

5+
> **<sup>Syntax</sup>**
6+
> _ArrayExpression_ :
7+
> &nbsp;&nbsp; &nbsp;&nbsp; `[` `]`
8+
> &nbsp;&nbsp; | `[` [_Expression_] ( `,` [_Expression_] )<sup>\*</sup> `,`<sup>?</sup> `]`
9+
> &nbsp;&nbsp; | `[` [_Expression_] `;` [_Expression_] `]`
10+
511
An _[array](types.html#array-and-slice-types) expression_ can be written by
612
enclosing zero or more comma-separated expressions of uniform type in square
713
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
2026
[1, 2, 3, 4];
2127
["a", "b", "c", "d"];
2228
[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
2431
```
2532

2633
## Array and slice indexing expressions
2734

35+
> **<sup>Syntax</sup>**
36+
> _IndexExpression_ :
37+
> &nbsp;&nbsp; [_Expression_] `[` [_Expression_] `]`
38+
2839
[Array and slice](types.html#array-and-slice-types)-typed expressions can be
2940
indexed by writing a square-bracket-enclosed expression (the index) after them.
3041
When the array is mutable, the resulting
@@ -50,4 +61,14 @@ let y = (["a", "b"])[n]; // panics
5061
5162
let arr = ["a", "b"];
5263
arr[10]; // panics
64+
65+
# let b = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
66+
b[1][2]; // multidimensional array indexing
5367
```
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

Comments
 (0)