Determining the size of a variable

January 8, 2025

Package unsafe

The functions Alignof and Sizeof take an expression x of any type and return the alignment or size, respectively, of a hypothetical variable v as if v was declared via var v = x.

Grammar nit! That should be “…as if v were…”

But nobody cares about that.

While Alignof is unlikely to be used outside of CGO, or low-level optimizations, Sizeof can be useful for us mere mortals.

unsafe.Sizeof will tell you how much memory the zero value of a variable uses.

var x []int
var y []int = []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

fmt.Println(unsafe.Sizeof(x), unsafe.Sizeof(y)) // prints: 24 24

So how can you get the size of an initialized variable, which differs from its zero value? There’s no built-in support for this in Go, but with some trivial (though annoyingly verbosse) mathematics, we can derive the runtime size. Here’s an exmaple, using the linked code:

import "/github.com/DmitriyVTitov/size"

var x []int
var y []int = []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

fmt.Println(size.Of(x), size.Of(y)) // prints: 24 104

Quotes from The Go Programming Language Specification Language version go1.23 (June 13, 2024)


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe