go / expert
Snippet
Zero-Allocation Slice Headers from Fixed-Size Array Pointers
By obtaining a slice full-range expression [:] directly on a pointer to a fixed-size array, Go creates a slice header pointing directly to the contiguous memory block of the array without copying data or invoking heap allocations.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package mainimport ("fmt""unsafe")func arrayToSliceHeader(arrPtr *[4]uint64) []uint64 {return (*[4]uint64)(unsafe.Pointer(arrPtr))[:]}func main() {arr := [4]uint64{0xDEAD, 0xBEEF, 0xCAFE, 0xBABE}slice := arrayToSliceHeader(&arr)fmt.Printf("Len: %d, Cap: %d, Val: %X\n", len(slice), cap(slice), slice[1])}
Breakdown
1
func arrayToSliceHeader(arrPtr *[4]uint64) []uint64 {
Defines a function accepting a pointer to a fixed 4-element uint64 array and returning a uint64 slice.
2
return (*[4]uint64)(unsafe.Pointer(arrPtr))[:]
Converts the raw pointer into an array pointer and applies full slicing [:] to derive a slice header pointing to original backing memory.
3
slice := arrayToSliceHeader(&arr)
Passes the memory address of the fixed-size array to derive the zero-copy slice.