Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Array and indexing grammar #133

Merged
merged 2 commits into from
Dec 1, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion src/expressions/array-expr.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

## Array expressions

> **<sup>Syntax</sup>**
> _ArrayExpression_ :
> &nbsp;&nbsp; &nbsp;&nbsp; `[` `]`
> &nbsp;&nbsp; | `[` [_Expression_] ( `,` [_Expression_] )<sup>\*</sup> `,`<sup>?</sup> `]`
> &nbsp;&nbsp; | `[` [_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
Expand All @@ -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

> **<sup>Syntax</sup>**
> _IndexExpression_ :
> &nbsp;&nbsp; [_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
Expand All @@ -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;
Expand All @@ -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