Empty struct
suggest changeA struct is a sequence of named elements, called fields, each of which has a name and a type. Empty struct has no fields, like this anonymous empty struct:
var s struct{}
Or like this named empty struct type:
type T struct{}
The interesting property of the empty struct is that its size is zero:
fmt.Println(unsafe.Sizeof(s))
This prints 0, so a value of the empty struct takes no memory. That makes struct{} a useful payload for a channel that only signals completion:
package main
import (
"fmt"
"time"
)
func main() {
done := make(chan struct{})
go func() {
time.Sleep(1 * time.Second)
close(done)
}()
fmt.Println("Wait...")
<-done
fmt.Println("done.")
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents