Advanced Go

Unsafe and C Boundaries

Understand what guarantees are lost when using unsafe or cgo and how to isolate the risk.

What you will learn

By the end of this lesson, you will be able to:

  • explain why unsafe operations fall outside normal type guarantees;
  • identify lifetime, alignment, size, and garbage-collector hazards;
  • define ownership at a C boundary;
  • decide whether cgo cost and deployment constraints are acceptable;
  • isolate unavoidable unsafe code behind a small tested API.

Begin with a presumption against it

Package unsafe allows operations that can bypass Go's type system and memory-safety assumptions. Code may depend on representation details that change across architectures or Go releases.

Use it only when a concrete requirement cannot be met clearly through normal Go, the standard library, maintained bindings, or code generation—and when tests and maintenance ownership are available.

What unsafe.Pointer changes

unsafe.Pointer is a special pointer type that permits certain conversions between pointer representations. Only documented conversion patterns are valid.

Risks include:

  • pointing at storage after its valid lifetime;
  • constructing misaligned pointers;
  • reading or writing the wrong size;
  • violating garbage collector pointer-tracking rules;
  • depending on field layout or padding;
  • retaining pointers through integer conversions incorrectly;
  • breaking under a different architecture or compiler version.

Do not infer legal patterns from code that happens to work in one test.

Prefer safe standard helpers

Modern Go provides safe or narrowly specified APIs for many previous unsafe use cases:

  • encoding/binary for binary representation;
  • math.Float64bits and related functions for numeric bit patterns;
  • slices, bytes, and strings for common conversions and operations;
  • reflect when runtime inspection is truly required;
  • code generation for repetitive typed adapters.

These APIs document ownership and portability better than hand-written pointer conversion.

Isolate the boundary

If unsafe code is necessary:

internal/platform/
  fastpath_amd64.go
  fallback.go
  fastpath_test.go
  • Keep the exported surface typed and safe.
  • Put assumptions in comments beside the operation.
  • Provide a safe fallback when practical.
  • Use build constraints only when platform differences are real and tested.
  • Test supported architectures and toolchain upgrades.
  • Benchmark the whole use case to prove the benefit.

The unsafe implementation should not leak unsafe.Pointer into ordinary application code.

What cgo does

cgo lets Go packages call C code and lets C interact with generated bindings. It may be appropriate for an existing native library, operating-system API, or performance-critical implementation that cannot reasonably be replaced.

It also introduces:

  • a C toolchain and platform-specific build requirements;
  • another memory-management system;
  • a boundary with calling and scheduling overhead;
  • more complex cross-compilation and distribution;
  • signal, thread, callback, and error-convention differences;
  • pointer-passing restrictions required by the Go garbage collector.

Measure boundary frequency. A small number of coarse calls can behave very differently from millions of tiny calls.

Define memory ownership

For every pointer crossing the boundary, document:

  • who allocated the memory;
  • which side may mutate it;
  • how long it remains valid;
  • who releases it and with which allocator;
  • whether the other side may retain the pointer after the call;
  • whether callbacks occur and on which thread assumptions.

Memory allocated by C generally must be released with the matching C API. Go memory follows Go's garbage collector and pointer-passing rules. Copy data when shared lifetime cannot be made safe and simple.

Error translation

C APIs may use return codes, errno, output parameters, or thread-local state. Translate these into stable Go errors at the boundary while preserving safe diagnostic context.

Never make callers manually combine a C pointer and a separate lifetime token if a typed Go wrapper can own both and expose Close.

type Handle struct {
    // unexported native state
}

func Open(...) (*Handle, error)
func (h *Handle) Close() error

Make repeated close behaviour explicit and prevent operations after close.

Validation tools

  • Run tests on every supported target.
  • Use go vet, the race detector where supported, platform sanitizers when applicable, and pointer checking offered by the current toolchain.
  • Fuzz safe parsing or marshalling layers around the boundary.
  • Test failure, empty input, maximum sizes, callbacks, cancellation, and repeated cleanup.

No tool proves unsafe code correct. Review invariants manually against current official rules.

Common mistakes

  • Converting through uintptr and retaining it: an integer is not a collector-tracked pointer or lifetime guarantee.
  • Returning a Go slice backed by temporary C memory: the slice outlives its storage.
  • Freeing C memory with a different allocator: allocator ownership is violated.
  • Making tiny cgo calls in a hot loop without measurement: boundary overhead dominates.
  • Using finalizers as the only native cleanup: release timing becomes nondeterministic.
  • Copying an unsafe snippet without its assumptions: context required for validity is lost.

Practice

Review a hypothetical image-decoding C wrapper. Produce an ownership table for input bytes, native decoder handle, output pixels, errors, callbacks, and cleanup. Design a safe Go API without writing unsafe conversion code.

Summary

  • unsafe trades away normal type and portability guarantees.
  • Use only conversion patterns documented by the current Go specification and package docs.
  • cgo adds a second toolchain, memory system, and lifecycle model.
  • Write down allocator, lifetime, mutation, retention, and cleanup for every crossing value.
  • Keep the risky core tiny and expose a safe typed API with extensive tests.

Official references: unsafe package and cgo command documentation.

Ready to wrap up?

Mark this complete when you can explain the main idea and finish the practice task.

Copyright © 2026