Package unsafe
…
The function
Slicereturns a slice whose underlying array starts atptrand whose length and capacity are len.Slice(ptr, len)is equivalent to(*[len]ArbitraryType)(unsafe.Pointer(ptr))[:]except that, as a special case, if
ptrisnilandlenis zero, Slice returns nil [Go 1.17].The
lenargument 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, iflenis negative, or ifptrisnilandlenis 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
SliceDatareturns a pointer to the underlying array of thesliceargument. If the slice’s capacitycap(slice)is not zero, that pointer is&slice[:1][0]. Ifsliceisnil, the result isnil. Otherwise it is a non-nilpointer to an unspecified memory address [Go 1.20].
Quotes from The Go Programming Language Specification Language version go1.23 (June 13, 2024)