Arrays and Slices

9.1 Static Arrays (Value Types)

int[5] a = [1, 2, 3, 4, 5];
int[3] zeros;                  // [0, 0, 0]
int[4] filled = 7;             // all 7
int[2][3] grid;                // 3 rows of int[2]
auto b = a;                    // COPIES (value semantics)
writeln(a.length, " ", a.sizeof);

9.2 Dynamic Arrays and Slices

A slice is a fat pointer (ptr + length). Slices share memory. Appending may reallocate (copy-on-append when the slice doesn't own the end of the memory block).

Bounds are checked in debug and @safe code. -boundscheck=off disables checks.

int[] arr = [1, 2, 3];
arr ~= 4;                      // append
arr ~= [5, 6];
arr.length = 10;               // resize (new elements = 0)
int[] s = arr[1 .. 4];         // slice: a view, no copy
s[0] = 99;                     // modifies arr too
int[] copy = arr.dup;          // independent copy
immutable(int)[] frozen = arr.idup;
writeln(arr[$ - 1], " ", arr[0 .. $]);   // $ = length
int[] made = new int[](5);     // allocate 5 zero-initialized ints
arr[] = 0;                     // set all elements
arr[] += 1;                    // array-wise operations (vectorizable)
int[] c = new int[](3);
c[] = arr[0 .. 3] * 2;
writeln(arr.capacity);
arr.reserve(100);
assumeSafeAppend(s);           // allow in-place append to a slice (advanced)

9.3 Multidimensional Arrays

int[][] jagged = [[1], [2, 3], [4, 5, 6]];
auto matrix = new int[][](3, 4);      // 3x4 dynamic
int[3][3] fixed;                      // static 3x3

9.4 Array Operations with Phobos

import std.algorithm, std.array, std.range;
int[] nums = [5, 3, 8, 1];
nums.sort();                                  // in-place (returns a SortedRange)
nums.sort!"a > b";                            // descending (string lambda)
nums.sort!((a, b) => a > b);
writeln(nums.canFind(3), nums.countUntil(8), nums.minElement, nums.maxElement);
writeln(nums.reverse, nums.sum, nums.uniq, nums.dup.sort.release);
auto evens = nums.filter!(x => x % 2 == 0).array;   // eager array from a lazy range
nums = nums.remove(1);                        // remove index 1
import std.algorithm.mutation : swap;