Package unsafe
…
The function
Slice
returns a slice whose underlying array starts atptr
and whose length and capacity are len.Slice(ptr, len)
is equivalent to(*[len]ArbitraryType)(unsafe.Pointer(ptr))[:]
except that, as a special case, if
ptr
isnil
andlen
is zero, Slice returns nil [Go 1.17].The
len
argument must be of integer type or an untyped constant. A constant len argument must be non-negative and representable by a value of typeint
; if it is an untyped constant it is given typeint
. At run time, iflen
is negative, or ifptr
isnil
andlen
is not zero, a run-time panic occurs [Go 1.17].
Let’s also look at the function signature from the documentation for this function, because it shows us something a bit interesting.
func Slice
func Slice(ptr *ArbitraryType, len IntegerType) []ArbitraryType
Notice that ArbitraryType
thing? Here’s how that is described:
ArbitraryType is here for the purposes of documentation only and is not actually part of the unsafe package. It represents the type of an arbitrary Go expression.
This function predates Go’s generics. So if you’re confused about this, maybe this framing will help:
func Slice[T any](ptr *T, int len) []T
And before I finish for today, let’s talk about the related SliceData
function:
The function
SliceData
returns a pointer to the underlying array of theslice
argument. If the slice’s capacitycap(slice)
is not zero, that pointer is&slice[:1][0]
. Ifslice
isnil
, the result isnil
. Otherwise it is a non-nil
pointer to an unspecified memory address [Go 1.20].
Quotes from The Go Programming Language Specification Language version go1.23 (June 13, 2024)