Sizeof and Alignof
- Go course
- Advanced
- Lesson 9/68
- 4 min
Learn memory layout with Sizeof and Alignof.
Sizeof and Alignof
unsafe.Sizeof gives a type's size in bytes, and unsafe.Alignof the byte boundary it must be placed on in memory. On a 64-bit system int64 is 8 bytes and aligned to 8.
fmt.Println(unsafe.Sizeof(int16(0)), unsafe.Alignof(int16(0))) // 2 2Both are constants computed at compile time.
Field order and padding
Ordering fields from largest to smallest reduces padding:
type Kotu struct { a bool; b int64; c bool } // 24 bytes
type Iyi struct { b int64; a bool; c bool } // 16 bytesIn slices holding millions of records this means real memory savings. The fieldalignment tool suggests this ordering.
Practice See the padding
Define type A struct { x bool; y int64; z bool } and type B struct { y int64; x bool; z bool }. Print the unsafe.Sizeof of both on one line.
Starter code
package main
import (
"fmt"
"unsafe"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"unsafe"
)
type A struct {
x bool
y int64
z bool
}
type B struct {
y int64
x bool
z bool
}
func main() {
fmt.Println(unsafe.Sizeof(A{}), unsafe.Sizeof(B{}))
}Expected output
24 16
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 On a 64-bit system, how many bytes is <code>struct{ a bool; b int64 }</code>?
- 10
- 16 Correct answer
- 9
- 8
Explanation: Field b must be aligned to 8, so 7 bytes of padding follow a: 1 + 7 + 8 = 16.
2 Ask the alignment
var x int64
fmt.Println(unsafe.____(x)) // 8
var x int64
fmt.Println(unsafe.Alignof(x)) // 8
Explanation: Alignof returns the type's memory alignment.
3 Memory layout
| Term | Meaning |
|---|---|
Sizeof |
Total bytes |
Alignof |
Alignment boundary |
Padding |
Empty bytes for alignment |
Field ordering |
Reduces padding |