Summary - unsafe
- Go course
- Advanced
- Lesson 12/68
- 4 min
Combine unsafe.Pointer and Sizeof to write a memory inspector.
unsafe summary
In this group you measured memory layout with Sizeof, Alignof and Offsetof; converted pointer types with unsafe.Pointer; and did zero-copy conversions with unsafe.String and unsafe.Slice.
Three rules: don't store a uintptr, don't modify the bytes of a zero-copy string, and look for a safe alternative first (e.g. math.Float64bits).
A tool that inspects a struct
Using the three functions together you can produce a layout report for a struct:
var h Hesap
fmt.Println("boyut:", unsafe.Sizeof(h))
fmt.Println("bakiye:", unsafe.Offsetof(h.Bakiye))This report shows whether reordering fields in a frequently used struct would save memory.
Practice Layout report
Define type Kayit struct { Aktif bool; ID int64; Puan int32 }. Print the struct's Sizeof and the Offsetof of ID and Puan on one line.
Starter code
package main
import (
"fmt"
"unsafe"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"unsafe"
)
type Kayit struct {
Aktif bool
ID int64
Puan int32
}
func main() {
var k Kayit
fmt.Println(unsafe.Sizeof(k), unsafe.Offsetof(k.ID), unsafe.Offsetof(k.Puan))
}Expected output
24 8 16
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a constant computed at compile time?
- unsafe.String(p, n)
- uintptr(p)
- unsafe.Sizeof(x) Correct answer
- unsafe.Pointer(&x)
Explanation: Sizeof, Alignof and Offsetof are computed at compile time; conversions happen at run time.
2 Address arithmetic
pb := (*int32)(unsafe.____(p, unsafe.Offsetof(k.b)))
pb := (*int32)(unsafe.Add(p, unsafe.Offsetof(k.b)))
Explanation: unsafe.Add adds bytes to a pointer without needing a uintptr conversion.
3 Rule and reason
| Term | Meaning |
|---|---|
Storing a uintptr |
GC doesn't treat it as a pointer |
Modifying the bytes |
Strings are immutable |
Order the fields |
Padding shrinks |
Safe alternative |
Portable code |