Member-only story
Efficient Go: Save Memory with Empty struct{}
Go is known for its simplicity and performance, but there are small idioms that can have a surprisingly big impact — especially when it comes to memory usage. One such idiom is the use of the empty struct, written as struct{}.
In this post, we’ll explore:
- What
struct{}is - Why it takes zero bytes
- Where it can help you save memory
- Practical examples to use it effectively
🤔 What is struct{} in Go?
In Go, struct{} is a struct with no fields. That means it holds no data and requires no storage. It’s the smallest possible data structure in Go.
type Empty struct{}Under the hood, the Go compiler optimizes this to take up zero bytes of memory.
🧠 Why Does struct{} Use 0 Bytes?
Since struct{} has no fields, Go has no reason to assign it memory. In fact, if a struct has only struct{} fields, the entire struct could still occupy zero bytes, unless alignment or padding is needed.
This is in contrast to other types, even if they contain minimal data:
var b bool // takes 1 byte
var i int // takes 4 or 8 bytes…