In Go, structs are the primary way to group related data together into a single, composite type. They are similar to classes in other languages but without inheritance.
Structs are especially useful when you want to represent real-world entities or complex objects with multiple fields.
type Person struct {
Name string
Age int
Email string
}
Person is a new struct type.Name, Age, and Email.// Using field names
p1 := Person{Name: "Alice", Age: 30, Email: "[email protected]"}
// Using positional fields
p2 := Person{"Bob", 25, "[email protected]"}
// Empty struct
p3 := Person{} // all fields get zero values
fmt.Println(p1.Name) // Alice
p1.Age = 31 // update field
You can attach methods to structs to give them behavior:
func (p Person) Greet() string {
return "Hello, my name is " + p.Name
}
fmt.Println(p1.Greet()) // Hello, my name is Alice
| Purpose | Explanation |
|---|---|
| Data grouping | Combine related fields (like a record or object). |
| Model real-world entities | Represent things like User, Order, Car, etc. |
| Attach behavior | Methods can be defined on structs. |
| Type safety | Each struct is a distinct type. |
| Composability | Structs can embed other structs to share fields. |