Offsetof
- Go course
- Advanced
- Lesson 10/68
- 4 min
Learn struct field offset with Offsetof.
Offsetof
unsafe.Offsetof(s.f) tells how many bytes after the start of the struct a field begins. This shows where padding was added.
type K struct { a bool; b int32 }
var k K
fmt.Println(unsafe.Offsetof(k.b)) // 4a is 1 byte, then 3 bytes of padding; b starts at 4.
Computing a field address
A field's address can be found by adding Offsetof to the struct's start address; since Go 1.17 unsafe.Add makes this readable:
p := unsafe.Pointer(&k)
pb := (*int32)(unsafe.Add(p, unsafe.Offsetof(k.b)))
*pb = 9Normal code just writes k.b = 9; this technique is used in serialization and sharing data with C.
Practice Field offsets
Define type R struct { a bool; b int32; c int64 }. For var r R, print the Offsetof of fields b and c on one line.
Starter code
package main
import (
"fmt"
"unsafe"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"unsafe"
)
type R struct {
a bool
b int32
c int64
}
func main() {
var r R
fmt.Println(unsafe.Offsetof(r.b), unsafe.Offsetof(r.c))
}Expected output
4 8
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>Offsetof</code> apply to?
- A struct field selector (s.f) Correct answer
- A type name
- A pointer
- A slice
Explanation: Offsetof expects a field selector of the form s.f and returns that field's byte offset.
2 Find the offset
var k Kayit
fmt.Println(unsafe.____(k.Yas))
var k Kayit
fmt.Println(unsafe.Offsetof(k.Yas))
Explanation: Offsetof returns the field's byte offset inside the struct.
3 Function and argument
| Term | Meaning |
|---|---|
Offsetof |
k.field |
Sizeof |
Any value |
unsafe.Add |
Pointer and byte count |
unsafe.Pointer |
A pointer |