How do struct{} and struct{}{} work in Go?
As pointed out by izca:
Struct is a go keyword for defining struct types which are just user defined types composed of variables of whatever arbitrary type you decide.
type Person struct {
Name string
Age int
}
Structs can also be empty with Zero elements. However Struct{}{} has a different meaning. This is a composite struct literal. It inline defines a struct type and defines an struct and assigns no property.
emptyStruct := Struct{} // This is an illegal operation
// you define an inline struct literal with no types
// the same is true for the following
car := struct{
Speed int
Weight float
}
// you define a struct be do now create an instance and assign it to car
// the following however is completely valid
car2 := struct{
Speed int
Weight float
}{6, 7.1}
//car2 now has a Speed of 6 and Weight of 7.1
This line here just creates a map of empty struct literals which is perfectly legal.
make(map[type]struct{})
It is the same as
make(map[type]struct{
x int
y int
})
struct
is a keyword in Go. It is used to define struct types, which is a sequence of named elements.
For example:
type Person struct {
Name string
Age int
}
The struct{}
is a struct
type with zero elements. It is often used when no information is to be stored. It has the benefit of being 0-sized, so usually no memory is required to store a value of type struct{}
.
struct{}{}
on the other hand is a composite literal, it constructs a value of type struct{}
. A composite literal constructs values for types such as structs, arrays, maps and slices. Its syntax is the type followed by the elements in braces. Since the "empty" struct (struct{}
) has no fields, the elements list is also empty:
struct{} {}
| ^ | ^
type empty element list
As an example let's create a "set" in Go. Go does not have a builtin set data structure, but it has a builtin map. We can use a map as a set, as a map can only have at most one entry with a given key. And since we want to only store keys (elements) in the map, we may choose the map value type to be struct{}
.
A map with string
elements:
var set map[string]struct{}
// Initialize the set
set = make(map[string]struct{})
// Add some values to the set:
set["red"] = struct{}{}
set["blue"] = struct{}{}
// Check if a value is in the map:
_, ok := set["red"]
fmt.Println("Is red in the map?", ok)
_, ok = set["green"]
fmt.Println("Is green in the map?", ok)
Output (try it on the Go Playground):
Is red in the map? true
Is green in the map? false
Note that however it may be more convenient to use bool
as the value type when creating a set out of a map, as the syntax to check if an element is in it is simpler. For details, see How can I create an array that contains unique strings?.