Variable Alignment

January 13, 2025

Package unsafe

Computer architectures may require memory addresses to be aligned; that is, for addresses of a variable to be a multiple of a factor, the variable’s type’s alignment. The function Alignof takes an expression denoting a variable of any type and returns the alignment of the (type of the) variable in bytes. For a variable x:

uintptr(unsafe.Pointer(&x)) % unsafe.Alignof(x) == 0

I don’t think I’m qualified to really talk much more about this. Variable alignment is not something I’ve ever had to deal with, and it’s far enough outside my wheelhouse that even in the theoretical sense, I don’t have a strong enough grasp on it to produce even a toy example of when it would be useful.

I do find the GoDoc for unsafe.Alignof package to be slightly more understandable, for what that’s worth:

Alignof takes an expression x of any type and returns the required alignment of a hypothetical variable v as if v was declared via var v = x. It is the largest value m such that the address of v is always zero mod m.


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