unsafe

Guided tour · Reflection & Unsafe · pkg.go.dev →

Escape hatch: bypass type safety for pointer arithmetic, zero-copy conversions, and layout tricks. Breaks portability if misused.

Sizes and alignment

Sizeof / Alignof / Offsetof

type T struct { A int32; B int64 }
var t T
unsafe.Sizeof(t)        // total bytes
unsafe.Alignof(t.B)     // alignment of field
unsafe.Offsetof(t.B)    // byte offset of field in struct

String and slice conversions

Go 1.20+ helpers for zero-copy interop.

String <-> []byte, zero copy

// string from byte slice (read-only):
s := unsafe.String(unsafe.SliceData(b), len(b))

// byte pointer from string:
p := unsafe.StringData(s)
b := unsafe.Slice(p, len(s))

// IMPORTANT: the string data must not be mutated.

Build a slice from a C-style pointer

s := unsafe.Slice(ptr, n) // []T of length n backed by ptr

unsafe.Pointer rules

Only these conversions are valid — anything else is undefined.

Allowed conversions

// 1. *T1 <-> unsafe.Pointer <-> *T2  (same memory)
// 2. unsafe.Pointer <-> uintptr        (arithmetic, but uintptr is NOT a GC root)
// 3. Use in syscall.Syscall or similar where required.