Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Logging, Flags and Testing

Go unsafe package

Reference for Go's unsafe package: Sizeof, Alignof, Offsetof, Pointer, Add, String, Slice and the rules that keep unsafe code valid.

The unsafe package lets a Go program step around the type system. It can report the exact memory size and layout of a type, convert between pointer types, do pointer arithmetic, and build strings and slices directly over existing memory. Nothing in it is checked by the compiler for correctness, and programs that use it are not covered by the Go 1 compatibility promise in the same way.

Most code never needs it. The cases that do are performance-critical conversions (a []byte to a string without copying), reading binary layouts, and interoperating with C or system calls. Always reach for a safe alternative first.

Go
import "unsafe"

var n int64
size := unsafe.Sizeof(n) // 8, a constant known at compile time

Try it

Go Size, alignment and field offsets

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.

Go Pointer arithmetic, String and Slice

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.

Syntax

Go
type ArbitraryType int // stands for any Go type
type IntegerType int   // stands for any integer type
type Pointer *ArbitraryType

func Sizeof(x ArbitraryType) uintptr
func Alignof(x ArbitraryType) uintptr
func Offsetof(x ArbitraryType) uintptr
func Add(ptr Pointer, len IntegerType) Pointer
func Slice(ptr *ArbitraryType, len IntegerType) []ArbitraryType
func SliceData(slice []ArbitraryType) *ArbitraryType
func String(ptr *byte, len IntegerType) string
func StringData(str string) *byte
Name Description
Pointer A pointer type that can hold the address of any variable. Only unsafe.Pointer converts to and from uintptr and to any *T.
Sizeof(x) Size in bytes of x itself, not of anything it points to. A string is 16 bytes on 64-bit systems whatever its text.
Alignof(x) The alignment, in bytes, that the type needs for its addresses.
Offsetof(x.f) Byte offset of field f from the start of its struct. The argument must be a selector expression.
Add(ptr, n) Returns ptr moved forward by n bytes (negative moves back).
Slice(ptr, n) A slice of length and capacity n starting at ptr.
SliceData(s) Pointer to the first element of the slice's backing array.
String(ptr, n) A string of n bytes starting at ptr, without copying.
StringData(s) Pointer to the first byte of the string's data.

Returns: Sizeof, Alignof and Offsetof return a uintptr constant, as long as the type has a fixed size (not a type parameter).

Edge cases: Slice and String panic if n is negative or the result would be larger than the address space. A nil ptr is only allowed with n == 0. The result of StringData for an empty string is unspecified, and you must never write through it.

Usage notes

  • The six valid pointer patterns. The package documentation lists exactly which conversions are legal: *T1 to *T2 when T2 is no larger and has compatible layout; Pointer to uintptr for printing; uintptr arithmetic only inside one expression such as unsafe.Pointer(uintptr(p) + off); calls like syscall.Syscall; reflect.Value pointer conversions; and reflect.SliceHeader/StringHeader rules. Anything else is undefined.
  • Never keep a uintptr as a pointer. A uintptr is just a number. The garbage collector ignores it, and the object it names may be moved or freed. Use unsafe.Add instead of uintptr math whenever possible.
  • Field order changes size. The compiler inserts padding to align fields, so ordering fields from largest to smallest often shrinks a struct, as the first example shows (24 bytes versus 16). The fieldalignment analyzer from golang.org/x/tools reports such cases.
  • Strings are immutable. After unsafe.String over a []byte, changing the bytes changes the string that other code may be using as a map key or a constant. Only do it if the bytes are never modified again.
  • Escape analysis still applies. Taking the address of a local and storing it as unsafe.Pointer keeps the variable alive correctly; storing only a uintptr does not.
  • Portability. Sizes depend on the platform (int is 4 or 8 bytes). Never hard-code layout numbers; compute them with Sizeof and Offsetof.
  • Vet helps. go vet includes the unsafeptr check, which flags many invalid uintptr to Pointer conversions. See go vet.
  • Added in Go 1.17 and 1.20: unsafe.Add and unsafe.Slice arrived in 1.17; SliceData, String and StringData in 1.20.