std / slice

slice

import "std:slice"

Provides low-level access to the internal memory layout of slices and strings. The Header type mirrors the {pointer, length} layout shared by all slice types and strings, enabling conversions between raw pointers and typed values via the assume operator.

View source on Codeberg →

Types

#
type Header struct {
    Ptr    uintptr
    Length int
}

Header mirrors the internal memory layout of all slice and string types: {pointer, length}. All slice types ([]int, []string, etc.) and the string type share this layout regardless of element type.

Use with the assume operator to convert between Header and typed slices:

// Typed slice from raw pointer:
h := slice.FromPointer(uintptr(ptr), count)
s := *(&h assume *[]string)

// Raw pointer from typed slice:
h := *(&s assume *slice.Header)
// h.Ptr and h.Length are the raw data pointer and length

Slice Construction

#
func FromPointer(ptr uintptr, length int) Header

Creates a slice Header from a raw pointer and length. Use with assume to obtain a typed slice.

#
func Decompose(a any) (uintptr, int)

Extracts the data pointer and length from a slice value boxed in an any parameter. The caller must ensure the any value actually contains a slice; passing a non-slice value produces undefined results.

String Construction

#
func StringFromPointer(ptr uintptr, length int) string

Creates a string from a raw byte pointer and length.

#
func StringDecompose(s string) (uintptr, int)

Extracts the data pointer and byte length from a string.