Arrays, maps & buffers
Choose the collection that fits its lifetime, size, and access requirements.
Hash maps#
map[K]V maps keys of type K to values of type V. Literals use key: value entries. Uninitialized declarations, zero(map[K]V), and make(map[K]V) create empty maps. Indexed writes insert or replace entries. A single-value read such as value := table[key] panics if the key does not exist. Use value, present := table[key] when absence is an expected outcome: a missing key returns the value type’s zero value and false; an existing key returns its stored value and true. The boolean reports whether the lookup succeeded. Neither read form inserts an entry. Missing-key panics use the ordinary panic mechanism and can be handled with defer and recover. len(table) counts entries and delete(table, key) removes a key if present.
Interfaces can be keys, values, or both. Unlike interface arrays, maps always permit mixed concrete types independently on both sides, with no mixed modifier. Each key and value must satisfy its declared interface. Boxed inputs are checked at runtime. Map assignments, arguments, and returns copy owned keys and values recursively. When assigning one map to another, the source and destination must have the same declared key type and the same declared value type. The key type does not have to equal the value type: map[string]int is valid. For example, a map[string]int cannot be assigned directly to a map[string]any, even though an individual integer can be stored in any; declare an interface-valued map when constructing it if you need mixed values.
Keys use Ocean equality: strings and aggregates compare contents, pointers compare addresses, and boxed primitive numeric keys use numeric equality. For example, 1 and 1.0 select the same entry in map[any]V. Two maps of the same type are equal when they contain the same keys and an equal value for each key. The order in which entries were inserted and the table’s internal bucket capacity do not affect that comparison. Range loops visit a snapshot in unspecified order; one binding receives keys and two receive keys and values. Entry addresses cannot be taken. The type written after map[K] is the complete value type. For example, map[string]int[] maps strings to dynamic integer arrays, and map[string]*int maps strings to integer pointers. To create an array of maps, first declare an alias such as type Counts = map[string]int;, then use Counts[].
counts := map[string]int{"Ocean": 1};
counts["Ocean"] += 1;
counts["compiler"] = 3;
value, present := counts["missing"]; // 0, false
size := len(counts); // 2
for (key, value := range counts) {
// key is string; value is int
}
delete(counts, "compiler");
items := map[any]any{1: "one", "two": 2, true: false};
Both the key side and value side of items contain different concrete types. This is the default behavior of interface maps.
Three collection forms#
T[] is a heap-backed dynamic array, T[n] is a sized array value, and buffer<T>[n] is raw contiguous storage. array<T> accepts sized arrays of any length. Ordinary array indexing checks bounds; raw buffer indexing is unchecked.
Start with a dynamic array when your collection needs to grow or shrink. Use a sized array when the value has a particular extent or when you want to pass a sized value through array<T>. Raw buffers are lower-level storage views and are mainly useful when an interface requires contiguous memory without Ocean’s ordinary array checks.
The three forms in the example below are sequential collections: positions are integer indices. Maps use keys of a declared type instead, as described above. Each sequential form specifies an element type. A literal body gives the initial elements, and an explicit declaration selects which collection representation receives them. The similar-looking syntax is worth reading carefully: a bracketed length in a declaration is different from a bare allocation expression.
| Form | Typical use |
|---|---|
T[] | A dynamic collection that can grow or shrink |
T[n] | An array value with a length in its type |
array<T> | A parameter or result accepting sized arrays of different lengths |
buffer<T>[n] | Raw storage with a length known in the declaring scope |
buffer<T>[] | A raw memory view; pass the element count separately |
dynamic := int[]{1, 2, 3};
fixed: int[3] = {1, 2, 3};
raw: buffer<int>[3] = {1, 2, 3};
The three declarations contain the same integer elements, but their permitted operations and storage behavior differ. dynamic supports mutation methods such as append; fixed has a length in its type; raw permits unchecked indexed access.
Grow and remove#
Dynamic arrays own their payload. append adds at the end, prepend adds at the beginning, and add inserts at an index. remove returns the removed element and shifts later values left. pop removes and returns the last element.
Insertion methods take values compatible with the element type. append and prepend can accept several values, and add(index, ...) inserts before the element currently at that index. These operations can replace the backing allocation as the collection grows.
remove and pop return a value that remains valid after the array changes. The removed value follows Ocean’s independent-copy rules. Nested owned data remains independently owned, so removing a string does not leave the result referring to freed collection storage. Invalid removal indices and popping an empty collection report a bounds error.
items := make(int[]);
items.append(2, 3);
items.prepend(1);
items.add(1, 8);
last := items.pop();
removed := items.remove(0);
The array becomes [2, 3], then [1, 2, 3], then [1, 8, 2, 3]. pop() returns 3; remove(0) then returns 1, leaving [8, 2]. make(int[]) starts with an empty dynamic array.
Copy and concatenate#
Array assignment, argument passing, and return create independent copies, including strings and other arrays stored inside the elements. If an element is a pointer, only its address is copied, so both arrays still refer to the same pointed-to object. For arrays, + constructs a concatenated value and += assigns that new value back to the variable on the left. These concatenation operators are not map operations.
Value semantics mean that ordinary assignment does not create two names for the same mutable payload. The compiler recursively copies owned collection contents, including dynamic arrays nested inside other arrays or structs. Explicit pointers are the exception: their address values are copied, so their pointees remain shared.
Concatenation follows the same copy rules. first + second produces a new collection without altering either input. Compound addition assigns that new result back to the variable on the left. You can also add a compatible single element at either end.
first := int[]{1, 2};
copy := first;
copy[0] = 99; // first[0] remains 1
joined := first + int[]{3, 4};
first += 5;
Changing copy[0] leaves first[0] equal to 1. joined receives [1, 2, 3, 4], and first += 5 replaces first with [1, 2, 5]. None of those operations changes copy afterward.
Checked access and sized arrays#
For arrays and strings, indexing with two bindings, such as value, ok := values[index];, returns an element and a boolean. If the index is outside the array, this form returns the element type’s default value and false. A single-binding read such as value := values[index]; instead reports a runtime bounds error for that invalid index. array<T> preserves runtime length when passing sized arrays. A dynamic array’s .array() method makes an independent sized-array copy.
Use the two-binding form when absence is an expected outcome you want to handle in the program. The success flag distinguishes a real zero-valued element from a failed lookup that also yields zero.
An array<int> parameter accepts sized integer arrays of different lengths while preserving their runtime extent. The length remains available through len(values), but is not fixed by the parameter’s declared type. array<int> describes a sized array of any length; int[] describes a growable dynamic array. They are different types. To supply a dynamic array’s current elements, call its .array() method to make a sized-array copy.
func first(values array<int>) (int, bool) {
value, ok := values[0];
return value, ok;
}
Calling first with a nonempty sized array returns its first element and true. An empty sized array gives 0 and false. The caller should use the flag to decide whether the value represents an actual element.
Slicing#
Slicing uses items[start:end], including start and excluding end. items[:], items[:2], items[2:], and items[1:2] are supported; omitted bounds default to zero and the collection length. For example, {0, 1, 2, 3, 4}[1:3] produces int[]{1, 2}. Arrays, dynamic arrays, and typed buffers produce a new dynamic array; strings produce a new string (sliced by byte). The result owns only the selected elements, with no shared backing storage, and nested owned values are copied recursively. Empty slices are valid. Bounds must satisfy 0 <= start <= end <= length; invalid bounds report a runtime bounds error. Unsized raw buffer pointers require an explicit end bound and the caller must ensure that the selected memory is valid.
values := {0, 1, 2, 3, 4};
part := values[1:3]; // int[]{1, 2}
all := values[:];
first := values[:2];
last := values[2:];
word := "ocean"[1:4]; // "cea"
Changing part[0] leaves values[1] unchanged. A string slice is a string; an array or buffer slice is a dynamic array.
Raw storage#
Use buffer<T>[] for an unsized raw view. Buffers do not provide ordinary bounds checks, and a raw buffer parameter does not retain a length recorded by the caller’s declaration. Pass the number of valid elements as a separate argument. Sized buffer declarations pad omitted literal elements with zero values.
An unsized buffer is a view of raw memory. Passing one to a function shares that memory instead of granting the function an independent length-aware collection. The separate count is part of the function’s contract: it must not exceed the valid memory available through the view.
This representation is useful for C interfaces and small low-level routines. It also removes checks that an ordinary array would provide, so keep the pointer and count together in the surrounding code. For example, the declaration data: buffer<int>[8]; makes the length eight available in the declaring scope. Passing data to a buffer<int>[] parameter does not make that length available inside the called function.
func fill(data buffer<int>[], count int) {
for (i := 0; i < count; i++) {
data[i] = i;
}
}
The function writes increasing integers into the first count elements. It assumes all those positions are valid. Use an array parameter instead when the function should receive a checked value with an available length.