Go provides a powerful way to define custom data types using structs. A struct is a composite data type that groups together variables (fields) under a single name. This allows you to create complex data structures that can represent real-world entities.
Structs are defined using the struct
keyword, followed by a list of fields enclosed in curly braces. Each field has a name and a type.
type Person struct {
Name string
Age int
}
The code above defines a struct named Person
with two fields: Name
of type string
and Age
of type int
. You can create an instance of a struct by using the struct type as a constructor.
Anonymous structs are structs that do not have a name. They are useful when you need a temporary data structure without defining a separate type. You can create an anonymous struct by using the struct
keyword directly.
Struct tags are annotations that can be added to struct fields. They are often used for serialization, validation, and other purposes. Tags are defined as a string literal following the field type.
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
In the example above, the struct fields Name
and Age
have JSON tags that specify how they should be serialized to JSON. The json:"name"
tag indicates that the Name
field should be represented as "name" in the JSON output.