array view


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
    

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);
}