A Team of Structs
Combine structs with slices and range loops.
1package main
2
3import "fmt"
4
5type Player struct {
6 name string
7 score int
8}
9
10func (p Player) cheer() {
11 fmt.Println("Go", p.name, "- score", p.score)
12}
13
14func main() {
15 ada := Player{name: "Ada", score: 100}
16 grace := Player{name: "Grace", score: 120}
17 players := []Player{ada, grace}
18 for _, player := range players {
19 player.cheer()
20 }
21}
$ go run main.go
Go Ada - score 100
Go Grace - score 120
Every line, explained
package main- Every Go file starts by saying which package it belongs to, exactly as in Intro to Go.
import "fmt"- import "fmt" brings in the printing tools, as always.
type Player struct {- type Dog struct { ... } defines a struct: a bundle of fields that belong together. Go has no classes; structs are how Go groups data, and they do the job beautifully. This one is for game players.
name string- This player's name.
score int- This player's score.
}- This } closes the struct definition.
func (p Player) cheer() {- The (d Dog) before the name is the receiver: it is what attaches this function to Dog values, turning it into a method. Inside, d is "the dog this method was called on".
fmt.Println("Go", p.name, "- score", p.score)- Uses both of this player's fields.
}- This } closes the function.
func main() {- func main() { ... } is where the program starts.
ada := Player{name: "Ada", score: 100}- One player...
grace := Player{name: "Grace", score: 120}- ...and another.
players := []Player{ada, grace}- Structs can go in a slice, just like numbers or strings!
for _, player := range players {- And range can visit each one in turn: everything from Intro to Go works with your own structs.
player.cheer()- Each player cheers with their own name and score. Structs, methods, slices and range: that is real Go!
}- This } closes the loop.
}- This } closes func main.