The Unsafe Package

The Unsafe Package in Go: A bench saw comes with a clear plastic guard over the blade. The guard is not what makes the saw cut -- the motor and the teeth do…

The Analogy: Removing the Guard From the Saw

A bench saw comes with a clear plastic guard over the blade. The guard is not what makes the saw cut -- the motor and the teeth do that. The guard exists to prevent one specific category of mistake: your hand arriving where the blade already is. Take it off and the saw cuts exactly as it did before, and for a few awkward jobs it cuts better, because the guard was in the way.

What actually changed is who is responsible. With the guard on, the machine enforces the rule. With it off, you do -- every second, from memory, with no second chance. A joiner who removes the guard for one specific cut, makes that cut, and puts it straight back is being professional. Someone who works with it off all day is not being fast; they are being lucky.

Go's unsafe package is that guard, removed. Everything the type system was quietly enforcing -- that a *int64 really points at eight bytes of int64, that a string's bytes are never written, that a pointer either references a live object or is nil -- becomes your problem instead of the compiler's. In exchange you get the ability to reinterpret memory with no copy and no per-field work, which is genuinely the only way to do a handful of jobs: talking to the operating system, matching a layout a C program defined, or turning a []byte into a string without allocating.

The honest framing is that unsafe is not a performance feature you reach for when code feels slow. It is an interoperability and zero-copy tool with a very short list of legitimate uses, most of which are already done for you inside syscall, sync/atomic and reflect. Its documentation states plainly that packages using it "may not be portable and are not protected by the Go 1 compatibility guidelines". The first part of learning it is learning the six conversion patterns the runtime actually promises to support; the second part is learning how rarely you need any of them.


Syntax or Core Structure

The safest and by far the most common use of the package is measurement. Sizeof, Alignof and Offsetof are compile-time constants, so importing unsafe for them generates no unsafe code whatsoever -- it just lets you see the layout the compiler chose.

package main

import (
	"fmt"
	"unsafe"
)

type Padded struct {
	Flag  bool  // 1 byte, then 7 wasted bytes so Count can be 8-aligned
	Count int64 // 8 bytes
	Code  int16 // 2 bytes, then 6 wasted bytes of tail padding
}

type Packed struct { // identical fields, declared largest-first
	Count int64
	Code  int16
	Flag  bool
}

func main() {
	var p Padded
	var q Packed

	fmt.Printf("Padded size=%d align=%d offsets: Flag=%d Count=%d Code=%d\n",
		unsafe.Sizeof(p), unsafe.Alignof(p),
		unsafe.Offsetof(p.Flag), unsafe.Offsetof(p.Count), unsafe.Offsetof(p.Code))
	fmt.Printf("Packed size=%d align=%d offsets: Count=%d Code=%d Flag=%d\n",
		unsafe.Sizeof(q), unsafe.Alignof(q),
		unsafe.Offsetof(q.Count), unsafe.Offsetof(q.Code), unsafe.Offsetof(q.Flag))

	// Sizeof is shallow: it measures the header, never the data behind it.
	s := []int64{1, 2, 3}
	str := "hello"
	fmt.Println("slice header:", unsafe.Sizeof(s), "string header:", unsafe.Sizeof(str))

	const size = unsafe.Sizeof(Padded{}) // a constant, usable as an array length
	var buf [size]byte
	fmt.Println("array sized by a constant:", len(buf))
}

Output (on a 64 bit platform):

Padded size=24 align=8 offsets: Flag=0 Count=8 Code=16
Packed size=16 align=8 offsets: Count=0 Code=8 Flag=10
slice header: 24 string header: 16
array sized by a constant: 24

Two identical sets of fields, a third of the memory saved purely by declaration order. Padded spends seven bytes idling after Flag so that Count can start on an 8-byte boundary, then six more at the end so the struct's own size is a multiple of its 8-byte alignment. Packed puts the widest field first and pays only five bytes of tail padding. This is not a micro-optimisation when the struct appears a million times in a slice -- and unsafe.Sizeof is how you find out, without guessing.


Technical Depth: Pointer, uintptr, and the Six Patterns

The whole package

NameSinceWhat it does
unsafe.Pointer1.0a pointer convertible to and from any pointer type
Sizeof, Alignof, Offsetof1.0compile-time constants describing layout
unsafe.Add(p, delta)1.17pointer arithmetic without writing uintptr yourself
unsafe.Slice(ptr, len)1.17build a []T over existing memory
unsafe.SliceData(s)1.20the *T a slice points at
unsafe.String, unsafe.StringData1.20the same pair for strings

Nine identifiers. There is no function in unsafe that reads or writes memory; every one of them is a conversion or a measurement.

unsafe.Pointer is a pointer; uintptr is a number

This is the distinction that every unsafe bug comes down to:

unsafe.Pointeruintptr
Garbage collectortracks it; keeps the object aliveignores it entirely
Stack growthupdated when the stack movesbecomes a stale address
Arithmeticnot allowedallowed
Dereferenceafter converting to a *Tnever

A uintptr is an integer that happens to have held an address. The moment you store one in a variable, you own an address the runtime has stopped protecting.

The six legal conversion patterns

The unsafe.Pointer documentation lists exactly six valid uses; anything else is undefined behaviour even if it appears to work.

PatternShapeCondition
1*T1 -> Pointer -> *T2T2 must be no larger than T1 and share an equivalent layout
2Pointer -> uintptrfine for printing or arithmetic on the value; never convert back later
3Pointer -> uintptr -> arithmetic -> Pointermust be one expression, and must stay inside the original object
4Pointer -> uintptr in a syscall.Syscall argumentthe compiler special-cases the call to keep the object alive
5reflect.Value.Pointer/UnsafeAddr result -> Pointermust be the same expression as the call
6Data field of a reflect.SliceHeader/StringHeadersuperseded by unsafe.Slice and unsafe.String -- do not use

Why "one expression" is a real rule

// WRONG: between the two statements the runtime may grow the goroutine's stack
// (which copies it) or, in a future release, move the heap object. u is a stale
// number the GC never knew about. "go vet" flags this shape as unsafeptr.
u := uintptr(unsafe.Pointer(&rec))
c := (*int64)(unsafe.Pointer(u + unsafe.Offsetof(rec.Count)))

// RIGHT: a single expression, so the pointer operand stays live throughout it.
c := (*int64)(unsafe.Pointer(uintptr(unsafe.Pointer(&rec)) + unsafe.Offsetof(rec.Count)))

// BETTER: unsafe.Add expresses the same thing with no uintptr in sight.
c := (*int64)(unsafe.Add(unsafe.Pointer(&rec), unsafe.Offsetof(rec.Count)))

Note that pattern 3 also requires the result to stay within the same allocated object. A pointer one byte past the end of an object is not a valid unsafe.Pointer, even if you never dereference it -- the one exception the docs grant is a pointer to the byte just past the end of a slice's backing array.

Zero-copy string and byte conversions

The one unsafe trick most Go programmers eventually meet:

// Valid only if b is never written again for as long as the string is used.
func asString(b []byte) string { return unsafe.String(unsafe.SliceData(b), len(b)) }

// Valid only if the result is never written to. Strings are immutable, and the
// compiler may have placed s in read-only memory, in which case a write faults.
func asBytes(s string) []byte { return unsafe.Slice(unsafe.StringData(s), len(s)) }

Both are correct conversions and both are trivially easy to misuse. strings.Clone and strings.Builder.String exist precisely so that ordinary code does not have to make this decision; reach for unsafe.String only inside a decoder whose lifetimes you can see end to end.

What still checks you, and what does not

go vet's unsafeptr analyser recognises the stored-uintptr shape and little else. Building with -race enables checkptr, a runtime instrumentation that reports misaligned conversions and pointers that stray outside their object -- it will not catch everything, but it catches a great deal, which is the strongest argument for running your unsafe code under go test -race. Nothing at all checks that a *T2 cast is layout-compatible, and nothing checks byte order.


Real World Example: Reading a Fixed-Layout Record

A file written by a C program, or a memory-mapped index, arrives as a []byte with a documented byte-for-byte layout. The ordinary decoder copies it field by field. The unsafe decoder reinterprets the bytes where they already are. Below, both are written side by side so one can check the other.

package main

import (
	"encoding/binary"
	"errors"
	"fmt"
	"unsafe"
)

// Header mirrors a 16-byte record produced by another program:
//
//	uint32 magic; uint16 version; uint16 flags; uint32 count; uint32 crc;
type Header struct {
	Magic   uint32
	Version uint16
	Flags   uint16
	Count   uint32
	CRC     uint32
}

const headerSize = 16

// Static assertions. A negative array length is a compile error, so these four
// declarations fail the BUILD if Go ever lays Header out differently than the
// file format requires. Struct layout is not covered by the Go 1 promise, and
// this is how you turn that risk into a broken build instead of corrupt data.
var (
	_ [unsafe.Sizeof(Header{}) - headerSize]byte
	_ [headerSize - unsafe.Sizeof(Header{})]byte
	_ [unsafe.Offsetof(Header{}.CRC) - 12]byte
	_ [12 - unsafe.Offsetof(Header{}.CRC)]byte
)

var (
	ErrShort = errors.New("buffer too short for a header")
	ErrAlign = errors.New("buffer is not aligned for a Header")
)

// decodeSafe copies field by field. It states its byte order explicitly, works
// at any alignment, and every step is checked by the compiler.
func decodeSafe(b []byte) (Header, error) {
	if len(b) < headerSize {
		return Header{}, fmt.Errorf("decode: %w: need %d, got %d", ErrShort, headerSize, len(b))
	}
	le := binary.LittleEndian
	return Header{
		Magic:   le.Uint32(b[0:4]),
		Version: le.Uint16(b[4:6]),
		Flags:   le.Uint16(b[6:8]),
		Count:   le.Uint32(b[8:12]),
		CRC:     le.Uint32(b[12:16]),
	}, nil
}

// decodeUnsafe reinterprets the bytes in place: no copy and no per-field work.
// It is defensible only because of the two guards, and only on a little-endian
// machine -- the cast reads whatever byte order the CPU uses.
func decodeUnsafe(b []byte) (*Header, error) {
	if len(b) < headerSize {
		return nil, fmt.Errorf("decode: %w: need %d, got %d", ErrShort, headerSize, len(b))
	}
	p := unsafe.Pointer(unsafe.SliceData(b))
	if uintptr(p)%unsafe.Alignof(Header{}) != 0 {
		return nil, fmt.Errorf("decode: %w", ErrAlign)
	}
	return (*Header)(p), nil // pattern 1: *byte -> Pointer -> *Header
}

func show(label string, h Header) {
	fmt.Printf("%-7s magic=%#x version=%d flags=%04b count=%d crc=%#x\n",
		label, h.Magic, h.Version, h.Flags, h.Count, h.CRC)
}

func main() {
	raw := make([]byte, 32)
	le := binary.LittleEndian
	le.PutUint32(raw[0:4], 0xCAFEBABE)
	le.PutUint16(raw[4:6], 3)
	le.PutUint16(raw[6:8], 0b1010)
	le.PutUint32(raw[8:12], 4711)
	le.PutUint32(raw[12:16], 0xDEADBEEF)

	safe, err := decodeSafe(raw)
	if err != nil {
		panic(err)
	}
	show("safe", safe)

	fast, err := decodeUnsafe(raw)
	if err != nil {
		panic(err)
	}
	show("unsafe", *fast)
	fmt.Println("identical:", safe == *fast)

	// The unsafe result aliases the buffer; the safe one is a copy.
	le.PutUint32(raw[8:12], 9000)
	fmt.Println("after patching raw, unsafe count =", fast.Count, "safe count =", safe.Count)

	_, err = decodeUnsafe(raw[:8])
	fmt.Println("short: ", err)
	_, err = decodeUnsafe(raw[1:17])
	fmt.Println("offset:", err)

	fmt.Printf("size=%d align=%d\n", unsafe.Sizeof(Header{}), unsafe.Alignof(Header{}))
}

Output (on a little-endian 64 bit platform):

safe    magic=0xcafebabe version=3 flags=1010 count=4711 crc=0xdeadbeef
unsafe  magic=0xcafebabe version=3 flags=1010 count=4711 crc=0xdeadbeef
identical: true
after patching raw, unsafe count = 9000 safe count = 4711
short:  decode: buffer too short for a header: need 16, got 8
offset: decode: buffer is not aligned for a Header
size=16 align=4

The two decoders agree, and then the patch line shows exactly what you bought. safe is a snapshot; fast is a window. For a single header that difference is a rounding error, but for a memory-mapped index of a million records it is the difference between copying sixteen megabytes and copying nothing, and between reading five fields and reading the one you asked about.

Three things make the unsafe path defensible rather than reckless. The static assertions come first: if a future toolchain, a different architecture, or a careless edit to Header changes the size or the offset of CRC, the package stops compiling instead of silently decoding the wrong bytes. The length check comes second, because unsafe performs no bounds checking at all -- casting an 8-byte buffer to a *Header reads eight bytes of whatever follows it, with no panic to tell you. The alignment check comes third: raw[1:17] is the right length but starts one byte into an allocation that the runtime handed back 8-byte aligned, so it cannot satisfy Header's 4-byte requirement. On amd64 a misaligned load merely costs cycles; on some architectures it faults, and under -race the checkptr instrumentation reports it outright.

What the fast path does not give you is byte order, and that is the bug this pattern produces in the field. decodeSafe says binary.LittleEndian in so many words and therefore decodes the same file identically on every machine. decodeUnsafe inherits the CPU's order, so the same binary compiled for a big-endian target reads 0xbebafeca and reports a bad magic number. Keeping the safe decoder in the file is not redundancy: it is the reference implementation, the test oracle, and the fallback behind a build tag for any architecture you cannot test on.

The judgement call is to measure before you reach for any of this. decodeSafe compiles to a handful of loads with no allocation, and for most workloads that is already free. Reach for unsafe when a profile says the copy dominates, keep both implementations, and write a fuzz target that feeds random bytes to each and asserts they agree -- go test -fuzz plus -race on the unsafe path is the closest thing to a safety guard you get once the real one is off.


Common Mistakes

  1. Storing a uintptr in a variable and converting it back later. The garbage collector does not treat it as a reference, and stack growth relocates stack objects, so the address can go stale between two adjacent lines. Do the arithmetic in one expression or use unsafe.Add.
  2. Trying to do arithmetic on an unsafe.Pointer directly. It is not an integer type. unsafe.Add(p, n) is the supported form.
  3. Declaring a reflect.SliceHeader or reflect.StringHeader as a local variable. Both are documented as unusable that way, because the Data field is a uintptr the GC cannot see. Use unsafe.Slice and unsafe.String.
  4. Writing through a []byte obtained from a string. Strings are immutable by contract and string constants may live in read-only pages, so the write either corrupts a value someone else is reading or faults outright.
  5. Casting to a wider type than the source holds. Pattern 1 requires T2 to be no larger than T1; a *[16]byte cast to a *[32]byte reads sixteen bytes that do not belong to you, silently.
  6. Ignoring alignment. A cast is not a load, so nothing complains until the load happens -- and on amd64 it may never complain at all, which is worse than a crash on the architecture that does fault.
  7. Expecting Sizeof to be deep. unsafe.Sizeof of a slice is 24 on a 64-bit machine no matter how many elements it holds, because it measures the header.
  8. Assuming struct layout is portable. Field order is respected, but padding, size and alignment differ across architectures and are explicitly outside the Go 1 compatibility promise.
  9. Letting the referenced object die. When you pass a uintptr to a syscall through anything other than the special-cased syscall.Syscall form, nothing keeps the object alive; runtime.KeepAlive is what extends its lifetime past the call.
  10. Trusting go vet to catch unsafe bugs. The unsafeptr check recognises one shape. Layout errors, alignment errors and byte-order errors are entirely invisible to it.
  11. Never running the unsafe path under -race. That build flag enables checkptr, which is the only automatic checking available -- skipping it discards the one safety net you still have.

Best Practices

  • Do not use unsafe until a profile proves the safe version is the bottleneck; encoding/binary, reflect and generics cover almost everything people reach for it to do.
  • Confine it to one small unexported file with a safe exported API, so the rest of the package stays ordinary Go and the audit surface stays one file long.
  • Assert every layout assumption at compile time with the negative-array-length trick, so a layout change breaks the build.
  • Check length before every cast and alignment before every reinterpretation; unsafe performs neither check for you.
  • Keep a safe reference implementation alongside the fast one and fuzz them against each other.
  • Run all tests that touch unsafe with -race so checkptr is active, and treat any checkptr report as a hard failure.
  • Use unsafe.Add, unsafe.Slice and unsafe.String in preference to hand-written uintptr arithmetic and to the deprecated reflect header structs.
  • Comment every unsafe conversion with the pattern number it relies on and the invariant the caller must maintain; the compiler no longer records it, so the comment is the only documentation.

Practice Exercises

  1. Declare three structs with the same five fields in different orders, print unsafe.Sizeof and every field offset for each, and explain the padding in the largest one byte by byte.
  2. Write asString and asBytes using unsafe.String/unsafe.Slice, then write a test that demonstrates the aliasing: convert a []byte to a string, mutate the slice, and show the string changing. Explain why that makes the function unsafe to export.
  3. Take the WRONG two-line uintptr example from this lesson, put it in a real program, and run go vet. Record its exact message, then fix it twice -- once with the single-expression form and once with unsafe.Add.
  4. Extend the Header example with a Records section: use unsafe.Slice to expose the bytes after the header as a []Record, add static assertions for Record's size, and write a fuzz target that checks the unsafe reader against an encoding/binary reader for random buffers.