diff --git a/src/expressions/array-expr.md b/src/expressions/array-expr.md index 00e81356d..8a1f8c113 100644 --- a/src/expressions/array-expr.md +++ b/src/expressions/array-expr.md @@ -2,6 +2,12 @@ ## Array expressions +> **Syntax** +> _ArrayExpression_ : +>       `[` `]` +>    | `[` [_Expression_] ( `,` [_Expression_] )\* `,`? `]` +>    | `[` [_Expression_] `;` [_Expression_] `]` + An _[array](types.html#array-and-slice-types) expression_ can be written by enclosing zero or more comma-separated expressions of uniform type in square 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 [1, 2, 3, 4]; ["a", "b", "c", "d"]; [0; 128]; // array with 128 zeros -[0u8, 0u8, 0u8, 0u8]; +[0u8, 0u8, 0u8, 0u8,]; +[[1, 0, 0], [0, 1, 0], [0, 0, 1]]; // 2D array ``` ## Array and slice indexing expressions +> **Syntax** +> _IndexExpression_ : +>    [_Expression_] `[` [_Expression_] `]` + [Array and slice](types.html#array-and-slice-types)-typed expressions can be indexed by writing a square-bracket-enclosed expression (the index) after them. When the array is mutable, the resulting @@ -43,6 +54,9 @@ _panicked state_ if it fails. ```rust,should_panic ([1, 2, 3, 4])[2]; // Evaluates to 3 +let b = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]; +b[1][2]; // multidimensional array indexing + let x = (["a", "b"])[10]; // warning: const index-expr is out of bounds let n = 10; @@ -51,3 +65,10 @@ let y = (["a", "b"])[n]; // panics let arr = ["a", "b"]; arr[10]; // panics ``` + +The array index expression can be implemented for types other than arrays and slices +by implementing the [Index] and [IndexMut] traits. + +[Index]: https://doc.rust-lang.org/std/ops/trait.Index.html +[IndexMut]: https://doc.rust-lang.org/std/ops/trait.IndexMut.html +[_Expression_]: expressions.html