A struct in Go is a collection of fields. It allows you to define custom data types and model real-world entities.
type Person struct {
Name string
Age int
}p1 := Person{Name: "Alice", Age: 30}
p2 := Person{"Bob", 25} // order matters
var p3 Person // zero-valued fieldsFields of a struct get default values if not initialized.
fmt.Println(p1.Name)
p1.Age = 31You can use a pointer to a struct to modify it efficiently:
func birthday(p *Person) {
p.Age++
}No need to use (*p).Field — Go lets you use p.Field directly with pointers.
people := []Person{
{Name: "Ava", Age: 22},
{Name: "Ben", Age: 28},
}Useful for building record lists, table rows, etc.
book := struct {
Title string
Pages int
}{"Go in Action", 300}Good for one-time usage without a named type.
Struct fields can include tags, often used for JSON or DB mapping:
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}Packages like encoding/json use these for marshaling.
Ask the AI if you need help understanding or want to dive deeper in any topic