Lexical
Array and range literals
Array literals in square brackets, inclusive ranges with .., and range spreading inside an array literal.
since 0.1.0-alpha.1linuxwindowswasm
Description
An array literal lists its elements in square brackets: [1, 2, 3]. The empty literal [] is an array with no elements. A literal has type Array<T>, and every element must have the element type.
a..b is a range literal. It is inclusive at both ends and has type Range. A Range has start and end fields, and it can be iterated in a for loop.
A range written inside an array literal is spread into the array: [1..3, 7] is [1, 2, 3, 7].
Array and range forms
Array<int> a = [1, 2, 3];
Array<int> empty = [];
Array<int> r = [1..5];
Array<int> mixed = [1..3, 7, 10..11];
console.writeln(a);
console.writeln(empty.length());
console.writeln(r);
console.writeln(mixed);
Range span = 1..10;
console.writeln(span.start);
console.writeln(span.end);
int total = 0;
for (int i in 1..4) {
total += i;
}
console.writeln(total);
[1, 2, 3]
0
[1, 2, 3, 4, 5]
[1, 2, 3, 7, 10, 11]
1
10
10
Rules
- An array literal is
[e1, e2, ...]. A trailing comma is a syntax error. - Elements must share the element type:
Array<int> a = [1, "x"];is a compile error. []takes its element type from the declaration it initializes.var e = [];has nothing to infer the type from.- A range element in an array literal is spread, and its bounds may be any
intexpression ([1..n]). a..bincludes bothaandb. A range whose end is below its start has no elements, sofor (int i in 5..3)never runs.- Array literals can be nested:
[[1, 2], [3]]is anArray<Array<int>>. - When an array literal initializes a sized numeric array such as
Array<byte>, every element, including those spread from a range, is converted to the element type.
Examples
Nested arrays, a range with a variable bound, and an empty range:
Nested arrays and variable bounds
Array<Array<int>> grid = [[1, 2], [3]];
console.writeln(grid);
int n = 3;
console.writeln([1..n]);
Array<string> names = ["a", 'b'];
console.writeln(names.length());
for (int i in 5..3) {
console.writeln("never printed");
}
console.writeln("done");
[[1, 2], [3]]
[1, 2, 3]
2
done
Notes
The Array and Range classes and their methods are documented under std.Array and std.Range.