go / expert
Snippet
Safe Low-Level Byte View Construction via Unsafe Slice and String Primitives
Go 1.20 standard library introduced `unsafe.StringData` and `unsafe.Slice`, providing type-safe unsafe memory primitives that bypass traditional Reflect header structures when constructing byte slices directly pointing to existing string buffers.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package mainimport ("fmt""unsafe")func ViewBytes(s string) []byte {if len(s) == 0 {return nil}return unsafe.Slice(unsafe.StringData(s), len(s))}func main() {str := "Antigravity core engine"bView := ViewBytes(str)fmt.Printf("View len=%d, first_byte=0x%x\n", len(bView), bView[0])}
Breakdown
1
return unsafe.Slice(unsafe.StringData(s), len(s))
Uses Go 1.20+ safe low-level primitives to build a byte slice header directly pointing to backing string bytes without heap allocation.
2
bView := ViewBytes(str)
Obtains a read-only slice view of the string memory payload.
3
fmt.Printf("View len=%d, first_byte=0x%x\n", len(bView), bView[0])
Reads underlying memory bytes safely while treating the underlying data as immutable.