unsafe.Slice

January 23, 2025

Package unsafe

The function Slice returns a slice whose underlying array starts at ptr 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 is nil and len 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 type int; if it is an untyped constant it is given type int. At run time, if len is negative, or if ptr is nil and len 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 the slice argument. If the slice’s capacity cap(slice) is not zero, that pointer is &slice[:1][0]. If slice is nil, the result is nil. 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)


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe