structs in Go: struct{} and struct{}{} Demystified
In Go, struct is a powerful construct used to define data types. However, there are two special cases of structs worth examining: struct{} and struct{}.
struct{}: The Zero-Element Struct
struct{} is a struct type with no named elements. It serves a few useful purposes:
Usage:
var emptyStruct struct{}
struct{}: Empty Composite Literal
struct{}{} is a composite literal that constructs an empty struct value. Composite literals allow for concisely initializing values of specific types. For struct{}, the syntax is simple:
var emptyStructValue = struct{}{}
Usage in a Set Implementation
One practical application of the empty struct is creating a set-like data structure using a Go map. Since a map only allows unique keys, we can use struct{} as the value type to create a set of unique elements without storing any values:
type Set map[string]struct{} func main() { set := make(Set) set["foo"] = struct{}{} set["bar"] = struct{}{} _, ok := set["foo"] println("Is \"foo\" in the set?", ok) }
Conclusion
struct{} and struct{}{} offer unique features that extend the utility of Go's struct system. The zero-element struct provides memory efficiency, while the empty composite literal assists in creating empty struct values or constructing set-like data structures.
The above is the detailed content of Go Structs: What's the Difference Between `struct{}` and `struct{}{}?`. For more information, please follow other related articles on the PHP Chinese website!