go / expert
Snippet
Reinterpreting Fixed-Array Memory to Slices using unsafe.Slice
The unsafe package allows zero-copy conversions between fixed-size array pointers and dynamic slices. unsafe.Slice constructs a slice backed by the provided pointer and length, allowing mutations in the slice to directly mutate the underlying array memory.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package mainimport ("fmt""unsafe")func main() {var arr [4]uint32 = [4]uint32{0x01, 0x02, 0x03, 0x04}ptr := unsafe.SliceData(arr[:])sl := unsafe.Slice(ptr, len(arr))sl[0] = 0xFFfmt.Printf("Original Array: %v\nReinterpreted Slice: %v\n", arr, sl)}
Breakdown
1
ptr := unsafe.SliceData(arr[:])
Obtains a raw pointer to the underlying backing array element.
2
sl := unsafe.Slice(ptr, len(arr))
Creates a slice header backed directly by the memory starting at ptr with the specified length.