Array View
An array view (also called a slice) is a lightweight descriptor that refers to a contiguous sequence of elements stored elsewhere in memory. It contains two fields: count, the number of elements, and data, a pointer to the first element. The type of an array view over elements of type T is written [] T.
An array view does not own the memory it points to. It is simply a window into data that lives somewhere else, whether that is a fixed array, a resizable array, or any other contiguous block of memory. Assigning one array view to another copies only the data pointer and count, never the underlying elements.
values: [4] int = .[10, 20, 30, 40];
view: [] int;
view.data = values.data;
view.count = values.count;
print("view[0] is %\n", view[0]); // 10
print("view.count is %\n", view.count); // 4
Views From Resizable Arrays
A resizable array can be assigned to an array view. This does not copy the array's elements. It creates a view by copying the resizable array's current data pointer and count into the array view. The view does not receive the resizable array's allocated capacity or allocator information.
values: [..] int;
array_add(*values, 10);
array_add(*values, 20);
view: [] int = values;
// view.data == values.data
// view.count == values.count
Because the view points at the resizable array's current storage, it can become stale if the resizable array later grows and moves its elements to a new allocation. Create the view after the resizable array has the contents you intend to read, or refresh the view after operations that may resize the array.
Subscripting
Array views support subscript access with bounds checking. Accessing an index outside the range 0 to count - 1 produces a runtime error.
view: [] int = ...;
x := view[2]; // Read the third element.
Taking Sub-Views
Because an array view is just a pointer and a count, you can create a sub-view of any contiguous range by adjusting data and count directly, without allocating or copying:
values: [5] int = .[10, 20, 30, 40, 50];
view: [] int;
view.data = values.data + 1;
view.count = 3;
// view now refers to [20, 30, 40]
Iteration
Array views can be iterated with a for loop, just like arrays:
for view {
print("index [%] has value %\n", it_index, it);
}