Sitemap
The Ordinary Programmer

The Ordinary Programmer is for coders who embrace simplicity and practicality. We share real-world tips, project stories, and tech insights for developers at every level. You don’t need to be a superstar — just a programmer who loves to learn and build helpful software.

Golang High-Performance Programming EP1: Empty Struct

The secret and application of the empty struct with a size of 0

4 min readJun 18, 2024

--

Press enter or click to view image in full size
Generate By DALLE-3

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.

Example

package main
​
import "fmt"
​
type emptyStruct struct…

--

--

The Ordinary Programmer
The Ordinary Programmer

Published in The Ordinary Programmer

The Ordinary Programmer is for coders who embrace simplicity and practicality. We share real-world tips, project stories, and tech insights for developers at every level. You don’t need to be a superstar — just a programmer who loves to learn and build helpful software.

huizhou92
huizhou92

Written by huizhou92

Golang backend engineer. Specializes in cloud, data, and security. Lifelong learner. Efficiency enthusiast.