Member-only story
Golang High-Performance Programming EP1: Empty Struct
The secret and application of the empty struct with a size of 0
The Mystery of the Empty Struct in Go: Understanding its Usage and Optimization
In Go, a regular struct typically occupies a block of memory. However, there’s a particular case: if it’s an empty struct, its size is zero. How is this possible, and what is the use of an empty struct?
type Test struct {
A int
B string
}
func main() {
fmt.Println(unsafe.Sizeof(Test{}))
fmt.Println(unsafe.Sizeof(struct{}{}))
}
/*
24
0
*/The Secret of the Empty Struct
Special Variable: zerobase
An empty struct is a struct with no memory size. This statement is correct, but to be more precise, it has a special starting point: the zerobase variable. This is a uintptr global variable that occupies 8 bytes. Whenever countless struct {} variables are defined, the compiler assigns the address of this zerobase variable. In other words, in Go, any memory allocation with a size of 0 uses the same address, &zerobase.
package main
import "fmt"
type emptyStruct struct…
