Skip to content
Tutorials Center
My learning

Topics

Lesson 123 of 147 ยท Advanced Go

unsafe, cgo and Assembly

Learn what Go's unsafe package really offers - Sizeof, Offsetof, unsafe.String and Slice, pointer arithmetic and its rules - plus cgo, assembly and WebAssembly targets.

Go protects you from a whole family of bugs that haunt other systems languages: no pointer arithmetic, no reinterpreting memory as a different type, no buffer overruns without a panic. Occasionally, though, you need to step outside those guardrails. You want to know exactly how big a struct is, convert a []byte to a string without copying, read a binary header straight out of a buffer, or call an existing C library.

Go provides escape hatches for all of these: the unsafe package, cgo for calling C, assembly files for hand-written machine code, and cross-compilation to WebAssembly. They share one rule: the compiler stops protecting you. A mistake is no longer a clean panic. It can be silent memory corruption that only shows up on another machine or in the next Go release. This lesson shows what each tool does, runs the safe parts of unsafe here, and tells you when to leave the rest alone.

Code that imports unsafe is not covered by the Go 1 compatibility promise. Programs that follow the documented patterns keep working, but code that "works by accident" can break with a new compiler, a new garbage collector or a different CPU architecture. Prefer safe code, and when you use unsafe, keep it in a few small, well-tested functions.

What the unsafe package contains

The package is tiny. It has one type and a handful of functions, all handled specially by the compiler:

Name Purpose
unsafe.Pointer A pointer that can be converted to and from any pointer type, and to and from uintptr
unsafe.Sizeof(x) Size in bytes of the value x (a compile-time constant for most types)
unsafe.Alignof(x) Required alignment of x
unsafe.Offsetof(s.f) Byte offset of field f inside struct s
unsafe.Add(p, n) p moved forward by n bytes (Go 1.17)
unsafe.Slice(p, n) A slice of n elements starting at pointer p (Go 1.17)
unsafe.String(p, n) A string of n bytes starting at byte pointer p (Go 1.20)
unsafe.StringData(s) / unsafe.SliceData(sl) The pointer to a string's or slice's first byte/element (Go 1.20)

Sizeof, Alignof and Offsetof are completely safe to call: they only report facts and never touch memory. You already met them in basic types and memory layout.

Sizes, alignment and offsets

CPUs read memory fastest when a value sits at an address that is a multiple of its size. The compiler therefore inserts padding between struct fields. Reordering fields can shrink a struct:

Go Sizeof, Alignof and Offsetof

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

On a 64-bit platform such as the server running this page, Wasteful takes 24 bytes (7 bytes of padding after A and 7 after C) while the same three fields reordered take 16. A string is 16 bytes (pointer and length), a slice 24 (pointer, length, capacity), a map one pointer-sized word (8) and an interface 16. On a 32-bit platform several of these numbers are smaller, which is why you print them instead of hard-coding them. Sorting fields from largest to smallest is a cheap optimization for structs you allocate by the million. A linter named fieldalignment reports wasteful orderings.

A normal Go pointer *T cannot be converted to *U. unsafe.Pointer can: it is the universal bridge. The rule is that you may only use it in patterns that the unsafe documentation lists, and the pattern you will use most is reinterpreting memory:

Go Reading the bits of a float

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Both lines print 0x3ff8000000000000, and after writing the bits of 2.0 through the uint64 view the float variable reads 2. That demonstrates the power and the point: math.Float64bits already exists, is just as fast, and cannot go wrong. Whenever the standard library offers a safe function (math.Float64bits, binary.LittleEndian.Uint32, strings.Builder), use it.

uintptr is not a pointer

uintptr is just an integer large enough to hold an address. The garbage collector does not treat it as a reference. This leads to the most important unsafe rule: do not keep a uintptr around. Converting a pointer to uintptr, doing arithmetic and converting back is only valid in the same expression:

Go
// Valid: the whole computation happens in one expression.
p2 := unsafe.Pointer(uintptr(unsafe.Pointer(p)) + offset)

// Invalid: the object might move or be collected between the two statements.
addr := uintptr(unsafe.Pointer(p))
p2 := unsafe.Pointer(addr + offset)

Since Go 1.17 you rarely need that pattern, because unsafe.Add does the arithmetic and keeps the value a real pointer. The example below walks an array element by element and reads a struct field through its offset:

Go Pointer arithmetic with unsafe.Add

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

This prints 10 20 30 40, then ID via offset: 7001, h.ID after write: 9 and header size: 8. Nothing here is more useful than nums[i] and h.ID, of course. Real code does this when the type is not known statically (that is how reflect and encoding/binary work internally) or when mapping a byte buffer onto a struct.

Go does no bounds checking on pointers made with unsafe.Add. Reading past the end of an array silently reads whatever happens to be there, or crashes the whole program with fatal error: unexpected signal. Stay inside memory you own.

Zero-copy strings and slices

Converting between string and []byte normally copies the data, because strings are immutable and byte slices are not (strings and runes). For a huge buffer in a hot path, the copy can matter. Go 1.20 added a clean, documented way to avoid it:

Go Zero-copy conversions: unsafe.String and unsafe.StringData

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The program prints hello, go, then Jello, go <- the string changed!, then Jello, go (copy) vs Hello, go. The second line shows exactly why the technique is dangerous: a Go string is supposed to be immutable (it can be a map key, be shared between goroutines, and be cached by the runtime), and modifying its bytes breaks every one of those assumptions. Go's own strings.Builder uses this trick internally, in a way that guarantees the buffer is never touched again. Use it only when profiling proves the copy is a bottleneck and you control every writer.

A word on what is not allowed

A few more rules of the unsafe.Pointer game, in short form:

  • Alignment: the target of a converted pointer must be correctly aligned for its type, and large enough. A *uint64 made from an odd address crashes on some CPUs.
  • Garbage collection: never store a pointer in a uintptr field or variable. Never hide pointers in integers or in memory the GC cannot see.
  • Types with pointers: do not reinterpret memory that holds Go pointers as plain integers, or vice versa.
  • Escape analysis: unsafe conversions can defeat optimizations. Read about stack and heap before assuming they make things faster.
  • Tooling: go vet includes the unsafeptr check for invalid uintptr to Pointer conversions, and running with -race and -d=checkptr (enabled automatically by -race) finds many misuses at run time.

cgo: calling C from Go

cgo lets Go code call C functions and use C types. You write a special comment block (the preamble) immediately before import "C", and the Go tool compiles the C code with the system's C compiler:

Go
package main

/*
#include <stdio.h>
#include <stdlib.h>

static int add(int a, int b) {
	return a + b;
}

static void greet(const char *name) {
	printf("Hello from C, %s!\n", name);
}
*/
import "C"

import (
	"fmt"
	"unsafe"
)

func main() {
	fmt.Println(C.add(2, 3)) // C.int converts to int

	name := C.CString("Gopher") // allocates C memory (malloc)
	defer C.free(unsafe.Pointer(name))
	C.greet(name)
}

On your machine, go run . prints 5 and Hello from C, Gopher!, provided a C compiler such as GCC or Clang is installed. It does not run in our editor, because the runner builds with CGO_ENABLED=0 and has no C toolchain.

The key facts:

  • C types appear as C.int, C.double, C.size_t, C.struct_point and so on; convert explicitly to Go types (int(C.add(1, 2))).
  • Strings are not shared. C.CString copies a Go string into malloced memory that you must free; C.GoString copies back.
  • Go memory passed to C must follow the cgo pointer-passing rules: C may not keep a pointer to Go memory after the call returns, and the memory passed may not itself contain Go pointers. Violating this is checked at run time and panics with cgo argument has Go pointer to unpinned Go pointer.
  • Each call crosses the boundary between Go's runtime and C's stack. It costs on the order of tens of nanoseconds, many times a normal Go call, so you cannot loop over a tiny C function a billion times and expect speed. Do big chunks of work per call.
  • A thread blocked in C is a thread the Go scheduler cannot use. It starts another thread for the other goroutines (scheduler internals).

The costs of cgo are not only speed. Cross-compiling becomes hard because you need a C cross-toolchain, you lose fully static, dependency-free binaries (unless you link statically), builds get slower, and tooling such as the race detector sees less. Most Go projects avoid it by choosing pure-Go libraries (for example, the pure-Go SQLite port modernc.org/sqlite instead of the C-based mattn/go-sqlite3). If you know C from the C tutorial, you already understand everything on the C side; cgo is only the glue.

Going the other way, a Go program can be built as a C-callable library with go build -buildmode=c-shared or c-archive, using //export comments, so that C, Python or Rust programs can call Go functions.

Assembly

Go also supports hand-written assembly in files with the .s extension, in Go's own assembler syntax. It is used almost exclusively in the standard library and in performance-critical packages (cryptography, math/big, hashing, internal/bytealg, SIMD routines). You declare the function in Go without a body and implement it in assembly:

Go
// add_amd64.go
package fast

func Add(a, b int64) int64
TEXT
// add_amd64.s
#include "textflag.h"

// func Add(a, b int64) int64
TEXT ยทAdd(SB), NOSPLIT, $0-24
	MOVQ a+0(FP), AX
	MOVQ b+8(FP), BX
	ADDQ BX, AX
	MOVQ AX, ret+16(FP)
	RET

You need a separate file per architecture, plus a pure-Go fallback with build tags. Assembly functions cannot be inlined, so for short functions a plain Go version is usually faster. For almost every application, the right amount of assembly is none; use the optimized standard library, and consult performance tuning instead.

WebAssembly targets

The Go compiler can also produce WebAssembly (Wasm), a portable binary format that runs in browsers and in server-side runtimes. Two targets exist, selected with environment variables, so no unsafe or cgo is involved:

Terminal
# Run in a browser (needs Go's wasm_exec.js glue and an HTML page)
GOOS=js GOARCH=wasm go build -o app.wasm

# Run under a WASI runtime such as wasmtime or wazero (Go 1.21+)
GOOS=wasip1 GOARCH=wasm go build -o app.wasm

The js/wasm target gives you the syscall/js package to call JavaScript APIs and manipulate the DOM. The wasip1 target gives a command-line program that can read files and standard input through the WebAssembly System Interface, which is well suited to plug-ins and sandboxed tools. Go's Wasm binaries are larger than those of Rust or C (they include the Go runtime and garbage collector, a few megabytes before compression). TinyGo is an alternative compiler that produces much smaller Wasm files. These details change quickly, so check the current release notes before committing to this path. The same compiler already cross-compiles to other operating systems through GOOS and GOARCH, as shown in how Go works.

Choosing the right tool

You want to... Use
Know a type's size or field offsets unsafe.Sizeof, Offsetof (safe)
Convert numbers to bits and back math.Float64bits, encoding/binary
Avoid copying a big buffer in a measured hot path unsafe.String, unsafe.Slice with strict ownership rules
Look at values of unknown type reflect
Use an existing C library cgo, or a pure-Go port
Hand-tune a hot loop with CPU instructions Assembly, only after profiling
Run Go in a browser or a sandbox GOOS=js or GOOS=wasip1

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement about uintptr is correct?

    uintptr is a plain integer. The GC does not follow it, so converting pointer to uintptr and back across statements is invalid. Use unsafe.Add instead.
  2. 2. On a 64-bit platform, struct{ a bool; b int64; c bool } and struct{ b int64; a bool; c bool } have sizes:

    The first layout needs padding after a and after c to align b and the struct (24 bytes). Putting the int64 first lets the two bools share the last word (16 bytes).
  3. 3. Why is unsafe.String(unsafe.SliceData(b), len(b)) dangerous?

    The string shares memory with the slice. Any later write to the slice silently modifies the string that other code assumes is constant.
  4. 4. Why does the code in the cgo section not run in this site's editor?

    cgo needs a C toolchain at build time. The runner builds pure Go only.
  5. 5. Which is a real downside of using cgo?

    Each call crosses a runtime boundary, and building needs a matching C toolchain. Goroutines and return values work fine.

Summary

  • unsafe gives you Sizeof, Alignof and Offsetof (safe, informative), plus Pointer, Add, Slice, String and StringData (powerful, unchecked).
  • Struct field order affects size because of padding; place large fields first when it matters.
  • Pointer-to-pointer conversions go through unsafe.Pointer; never keep a uintptr between statements. Prefer unsafe.Add.
  • Zero-copy string/byte conversions work only if nobody mutates the shared memory. Reach for them after profiling, not before.
  • unsafe code is outside the Go 1 compatibility promise; go vet and -race catch many mistakes.
  • cgo calls C code (import "C") at the cost of speed, build complexity and portability; assembly is for the standard library and hot kernels; GOOS=js and GOOS=wasip1 compile Go to WebAssembly.

Next: The Go Scheduler and Runtime Internals explains how goroutines are mapped onto operating-system threads.