Under heavy development. This site describes the intended 1.0 language. Current features and performance vary. Development status
Sn50SnThe SnAPI programming language
Development · Evolving reference

Vector

Owns a contiguous growable sequence and its explicit allocator value.

Sn is under heavy development. This reference includes the intended 1.0 design; features may be incomplete in the current compiler. Read the status →

Module std.collections

import std.collections;

Public declaration contracts and authored examples. A page can document several related symbols. Implementation bodies are excluded.

Vector

pub final class Vector<T, A = DefaultAllocator>
    where T: Movable
    where A: Allocator, Defaultable, Movable

Owns a contiguous growable sequence and its explicit allocator value.

Vector<T, A>() is allocation-free and contains no live element. Exactly [0, Length) slots are live. Structural mutation invalidates every cursor; the more precise element/slice invalidation rules follow the operation contracts below. Vector is non-Copy and its authored move transfers the buffer and allocator while leaving the source empty and destructible.

T: Movable element type. A: Structural allocator type; omission selects DefaultAllocator.

Example

module example.vector;
from std.collections import Vector;
from std.memory import DefaultAllocator;
fn Main() -> i32 {
    var Values = Vector<i32>.WithAllocator(default(DefaultAllocator));
    if !Values.IsEmpty || Values.Length != 0 || Values.Capacity != 0 {
        return 1;
    }
    if Values.TryReserve(4) is .Err { Error = _ } {
        return 2;
    }
    if Values.TryReserveAdditional(2) is .Err { Error = _ } {
        return 3;
    }
    if Values.TryPush(3) is .Err { Error = Failure } {
        return Failure.Value;
    }
    switch Values.TryInsert(1, 5) {
        case .Ok => { }
        case .Err { Error = Failure } => return Failure.Value;
    }
    if Values.TryInsert(1, 4) is .Err { Error = Failure } {
        return Failure.Value;
    }
    if Values.Length != 3 || Values.At(0) != 3 || Values[1] != 4 {
        return 4;
    }

    Values.At(0) = 2;
    var WritableView = Values.AsSlice();
    WritableView[2] = 6;
    let ReadView: readonly i32[] = Values.AsSlice();
    if ReadView[0] != 2 || ReadView[2] != 6 {
        return 5;
    }

    var ReadCursor = Values.CreateIterator();
    switch ReadCursor.Next() {
        case .Some { Value = Item } => {
            if Item != 2 { return 6; }
        }
        case .None => return 7;
    }
    var WriteCursor = Values.CreateWritableIterator();
    switch WriteCursor.Next() {
        case .Some { Value = Item } => Item += 1;
        case .None => return 8;
    }

    switch Values.TryReserveAdditional(18446744073709551615_usize) {
        case .Ok => return 9;
        case .Err { Error = Error } => {
            if Error != .SizeOverflow { return 10; }
        }
    }
    switch Values.Pop() {
        case .Some { Value = Item } => {
            if Item != 6 { return 11; }
        }
        case .None => return 12;
    }
    if Values.Remove(0) != 3 || Values.Length != 1 {
        return 13;
    }
    if Values.TryPush(9) is .Err { Error = Failure } {
        return Failure.Value;
    }
    if Values.TryPush(10) is .Err { Error = Failure } {
        return Failure.Value;
    }
    if Values.SwapRemove(0) != 4 || Values.Length != 2 {
        return 14;
    }
    Values.Truncate(1);
    if Values.Length != 1 || Values.TryShrinkToFit() is .Err { Error = _ } {
        return 15;
    }
    var Moved = move(Values);
    if !Values.IsEmpty || Moved.Length != 1 { return 18; }
    Values = move(Moved);
    if !Moved.IsEmpty || Values.Length != 1 { return 19; }
    Values.Clear();
    if !Values.IsEmpty {
        return 16;
    }
    if Values.TryShrinkToFit() is .Err { Error = _ } {
        return 17;
    }
    return 0;
}

Example

module example.vector_mutable_iterator;
from std.collections import Vector;
fn Sum(Values: readonly Vector<i32>&) -> i32 {
    var Cursor = Values.CreateIterator();
    var Total: i32 = 0;
    while Cursor.Next() is .Some { Value = Item } { Total += Item; }
    return Total;
}
fn Main() -> i32 {
    var Values = Vector<i32>();
    if Values.TryPush(20) is .Err { Error = _ } { return 1; }
    if Values.TryPush(20) is .Err { Error = _ } { return 2; }
    {
        var Cursor = Values.CreateIterator();
        while Cursor.Next() is .Some { Value = Item } { Item += 1; }
    }
    // Cursor scope ends before another operation on the owning sequence.
    return Sum(Values) - 42;
}

Vector.init

pub init()

Creates an empty Vector with the canonical allocator value.

Vector.init

pub init(mut Value: A)

Creates an empty Vector with a transferred allocator value. Value: Allocator owner consumed without allocating.

Vector.init

pub init(Source: readonly Self&) = delete;

Rejects copying an owning buffer. Source: Existing buffer owner; even an empty owner cannot be copied.

Vector.init

pub init(Source: mut Self&&)

Transfers a buffer and allocator into new Vector storage. Source: Writable source left empty with its moved-from allocator live.

Vector.operator

pub fn operator =(Source: readonly Self&) -> void = delete;

Rejects copying into a live owning buffer. Source: Existing buffer owner whose storage cannot acquire a second owner. Return: No runtime result; copy assignment is rejected at compile time.

Vector.operator

pub fn operator =(Source: mut Self&&) -> void

Releases the old buffer and moves the source buffer and allocator into this Vector. Source: Writable source left empty with its moved-from allocator live. Return: No value; exact self-assignment preserves the Vector unchanged.

Vector.WithAllocator

pub static fn WithAllocator(mut Value: A) -> Vector<T, A>

Creates an empty Vector owning a configured allocator value. Value: Allocator owner consumed without allocating. Return: Empty Vector with zero capacity and the transferred allocator.

Vector.Length

pub Length: usize;

Returns the live element count. Return: Zero through Capacity.

Vector.Capacity

pub Capacity: usize;

Returns the owned raw-slot count. Return: Capacity in elements.

Vector.IsEmpty

pub IsEmpty: bool;

Reports whether no element is live. Return: Length == 0.

Vector.AsSlice

pub readonly fn AsSlice() -> readonly T[]

Borrows the complete live prefix as a read-only slice. Return: Nonowning slice invalidated by reallocation and documented mutation.

Vector.AsSlice

pub fn AsSlice() -> mut T[]

Borrows the complete live prefix as a writable slice. Return: Nonowning writable slice invalidated by reallocation and mutation.

Vector.At

pub readonly fn At(Index: usize) -> T&

Borrows one bounds-checked element with read-only access. Index: Zero-based index strictly below Length. Return: Read-only reference invalidated under the Vector mutation rules. Warning: An out-of-range index fatal-traps in every profile.

Vector.At

pub fn At(Index: usize) -> mut T&

Borrows one bounds-checked element with writable access. Index: Zero-based index strictly below Length. Return: Writable reference invalidated under the Vector mutation rules. Warning: An out-of-range index fatal-traps in every profile.

Vector.CreateIterator

pub readonly fn CreateIterator() -> SliceIterator<T>

Creates a read cursor over the current live prefix. Return: Zero-allocation cursor invalidated by every structural mutation.

Vector.CreateIterator

pub fn CreateIterator() -> WritableSliceIterator<T>

Creates a writable cursor from a mutable receiver. Return: Caller-owned traversal state borrowing writable element references; creating the cursor neither allocates nor retains the buffer owner. Warning: Every structural mutation, move or destruction can invalidate the cursor and its yielded references under the Vector contract.

Vector.CreateWritableIterator

pub fn CreateWritableIterator() -> WritableSliceIterator<T>

Creates a writable cursor over the current live prefix. Return: Zero-allocation writable cursor invalidated by structural mutation.

Vector.TryReserve

pub fn TryReserve(MinimumCapacity: usize)
        -> Result<void, AllocationError>

Ensures capacity for at least MinimumCapacity elements. MinimumCapacity: Required lower bound. Return: Success or allocation/layout failure with a strong guarantee. Warning: Successful reallocation invalidates every alias and cursor.

Vector.TryReserveAdditional

pub fn TryReserveAdditional(Additional: usize)
        -> Result<void, AllocationError>

Ensures room for Additional elements beyond current Length. Additional: Extra element count required. Return: Success, SizeOverflow, or allocation failure with no mutation.

Vector.TryShrinkToFit

pub fn TryShrinkToFit() -> Result<void, AllocationError>

Reallocates to exactly Length slots, or releases an empty buffer. Return: Success or allocation failure with the original Vector unchanged. Warning: Successful capacity change invalidates every alias and cursor.

Vector.TryPush

pub fn TryPush(mut Item: T)
        -> Result<void, VectorInsertionError<T>>

Appends one transferred item. Item: Writable owned parameter transferred only on success. Return: Success, or failure retaining the original item and Vector state. Warning: Structural mutation invalidates every cursor; reallocation also invalidates every element alias and slice.

Vector.TryInsert

pub fn TryInsert(Index: usize, mut Item: T)
        -> Result<void, VectorInsertionError<T>>

Inserts one transferred item while preserving element order. Index: Position from zero through Length. Item: Writable owned parameter transferred only on success. Return: Success, or allocation failure retaining item and Vector state. Warning: Index above Length fatal-traps; success invalidates aliases at or after Index and every cursor.

Vector.Pop

pub fn Pop() -> T?

Removes and returns the last item when present. Return: None when empty, otherwise ownership of the former last value. Warning: Success invalidates the removed element and every cursor.

Vector.Remove

pub fn Remove(Index: usize) -> T

Removes one item while preserving the order of later elements. Index: Zero-based index strictly below Length. Return: Ownership of the removed value. Warning: Out-of-range fatal-traps; aliases at or after Index and every cursor are invalidated.

Vector.SwapRemove

pub fn SwapRemove(Index: usize) -> T

Removes one item by filling its slot from the former last item. Index: Zero-based index strictly below Length. Return: Ownership of the removed value. Warning: Out-of-range fatal-traps; removed/former-last aliases and every cursor are invalidated. Order may change.

Vector.Truncate

pub fn Truncate(NewLength: usize) -> void

Destroys tail elements until Length is at most NewLength. NewLength: Requested retained prefix length; values above Length do nothing. Return: No value after reverse-order tail destruction. Warning: Removed aliases and every cursor are invalidated.

Vector.Clear

pub fn Clear() -> void

Destroys every element while retaining allocation capacity. Return: No value after reverse-order destruction. Warning: Invalidates every element alias, slice, and cursor.

Documentation snapshot: October 24, 2026 About versions ↗
Searching Development · language & standard library