Skip to content
CryoCryo home
Stdlibcore

slice

import std::core::slice; — in the prelude · source

Slice<T>

type struct Slice<T> {
    ptr:    T*;
    length: u64;

    static from_raw(ptr: T*, length: u64) -> Slice<T>;
    length(&this) -> u64;
    is_empty(&this) -> boolean;
    get(&this, index: u64) -> Option<T>
    where T: Copy;
    get_ref(&this, index: u64) -> Option<T*>;
    as_ptr(&this) -> T*;
    subslice(&this, start: u64, end: u64) -> Slice<T>;
    iter(&this) -> implement Iterator<T>
    where T: Copy;
}

A Slice<T> is a (pointer, length) pair: a borrowed view into a contiguous run of values. Algorithms take slices, collections hand them out with as_slice(), and so each algorithm gets written once. for (x in arr) over a fixed-size T[N] lowers to Slice::from_raw, which is why the module is in the prelude.

A slice does not own its storage. The backing memory has to outlive every slice pointing into it.

MethodReturnsNotes
from_raw(ptr, length)Slice<T>You certify that the range is valid initialized memory.
length / is_emptyu64 / boolean
get(index) (where T: Copy)Option<T>Bounds-checked read by value.
get_ref(index)Option<T*>Bounds-checked borrow; sound for every T.
as_ptrT*Raw pointer to the first element; respect length.
subslice(start, end)Slice<T>[start, end). Panics if start > end or end > length.
iter (where T: Copy)implement Iterator<T>Yields elements by value. The concrete type is SliceIter<T>, whose count is O(1).

get and iter are gated on T: Copy because they produce an independent bitwise duplicate while the backing storage still owns the element — sound only when T carries no drop obligation. For an owning T, walk by index with length() and get_ref.

SliceIter<T>

type struct SliceIter<T> {
    ptr:       T*;
    remaining: u64;
}

The concrete type behind iter(): a pointer and a remaining count. Its count is O(1), where the trait default would walk the sequence.

implement<T> trait Iterator<T> for struct SliceIter<T>