Middle
What weight does an empty structure have in Go?
sobes.tech AI
Answer from AI
The size of an empty struct struct{} in Go is 0 bytes.
This is a language feature that allows using empty structs for various purposes without consuming memory. For example:
- To implement sets using a map
map[key]struct{}. Only the presence of the key matters, the value is irrelevant. - As a signal indicator in channels, where the fact of receiving a message is important, not its content.
// Example of using an empty struct for a set
set := make(map[string]struct{})
set["item1"] = struct{}{} // Add an element
_, exists := set["item1"] // Check for the element
fmt.Println(exists) // true
// Example of using an empty struct in a channel
ch := make(chan struct{})
go func() {
// Send a signal
ch <- struct{}{}
}()
// Wait for the signal
<-ch