go / expert
Snippet
Zero-Copy String to Slice Inspection via Unsafe Pointer Memory Primitives
Modern Go (1.20+) provides unsafe.StringData and unsafe.Slice to construct byte slice headers directly over immutable string backing arrays without heap allocations. While zero-copy conversions enhance read operations, mutating the resulting byte slice triggers undefined runtime behavior due to writing into read-only memory segments.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package mainimport ("fmt""reflect""unsafe")func readOnlyByteView(s string) []byte {if len(s) == 0 {return nil}return unsafe.Slice(unsafe.StringData(s), len(s))}func inspectSliceHeader(b []byte) (uintptr, int, int) {hdr := (*reflect.SliceHeader)(unsafe.Pointer(&b))return hdr.Data, hdr.Len, hdr.Cap}func main() {str := "Immutable Memory String"view := readOnlyByteView(str)ptr, l, c := inspectSliceHeader(view)fmt.Printf("Address: 0x%x, Length: %d, Capacity: %d\n", ptr, l, c)fmt.Printf("Content: %s\n", string(view))}
Breakdown
1
return unsafe.Slice(unsafe.StringData(s), len(s))
Creates a slice view pointing to the underlying bytes of string 's' without copying memory.
2
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&b))
Casts the slice address to access structural header metadata fields directly.