Is struct{} an idiom for a type whose content does not matter, but its presence does?
Is it the smallest type? Does it take less space than bool, or byte? Is its size zero?
A ran a test, and I think the answer is yes to all:
package main
import (
"fmt"
)
func main() {
for i := 0; i < 100; i++ {
a := make([]struct{}, 4000000000)
fmt.Println(i, len(a))
}
}
This program runs very quickly.
If I use byte instead of struct{}, the program gets stuck looking for memory.
An arrray of 0 size (such as [0]bool also has this property of zero size.
Yes, struct{} is the smallest type. I like to think of it like void in C but it’s actually instantiate-able. It is a struct but it also has no fields therefore takes no memory to be allocated. It’s useful for signalling completion or readiness. It’s also useful to implement a set type from a map a-la: