Introduction to Structs
Structs are used in Go to group different types of variables together into a single custom type. They are the closest thing Go has to objects or dictionaries in other languages.
Definition
You define a struct using the type and struct keywords.
type car struct {
brand string
model string
doors int
mileage int
}
Usage
Once defined, you can create instances of the struct and access its fields using the dot . operator.
myCar := car{
brand: "Toyota",
model: "Camry",
doors: 4,
}
fmt.Println(myCar.brand) // Toyota
myCar.mileage = 15000
Why use structs?
Structs allow you to pass complex data structures as a single unit, making your function signatures cleaner and your code more organized.