Structs: Model Real Things
Bundle related values into one type
Imagine tracking a player in a game: a name, a score, whether they are online. You could juggle three separate variables, but they belong together. A struct lets you bundle related values into one custom type, and it is the heart of how Go models the real world.
Defining a struct
type Player struct {
Name string
Score int
Online bool
}The type keyword creates a brand new type named Player, and the struct lists its fields: each field has a name and a type. This definition goes outside your functions, near the top of the file.
Creating and using a struct value
func main() {
p := Player{Name: "mia", Score: 12, Online: true}
fmt.Println(p.Name, "has", p.Score, "points")
p.Score = p.Score + 5
fmt.Println(p.Name, "now has", p.Score)
}You build a Player by naming each field and giving it a value. The dot reaches into the struct: p.Name is the Name field of p. Fields read and update just like normal variables.
Structs work with everything you know
Structs combine beautifully with functions and slices:
func describe(p Player) string {
if p.Online {
return p.Name + " is online"
}
return p.Name + " is offline"
}
func main() {
team := []Player{
{Name: "mia", Score: 12, Online: true},
{Name: "raj", Score: 9, Online: false},
}
for _, p := range team {
fmt.Println(describe(p))
}
}Here []Player is a slice of players, and the range loop hands each one to the describe function. Your whole toolkit is starting to click together.
A peek at methods
Go lets you attach a function directly to a type, which is then called a method:
func (p Player) Greeting() string {
return "Welcome back, " + p.Name + "!"
}
fmt.Println(p.Greeting())The extra (p Player) before the name means this function belongs to Player, and you call it with the dot: p.Greeting(). Methods are how Go types grow behavior, and they will feel familiar because you have been calling methods like this since fmt.Println.
Field names that start with a capital letter, like Name, are visible to other packages; lowercase ones are private to their own package. Capitals are a fine habit while you learn.
Quick check
Q1 What is a struct in Go?
Q2 Given p := Player{Name: "mia", Score: 12}, how do you read the score?
Want to save your progress? It's free.
Create a free account