Go, lesson 10
A game character has a name, health and a level. You could keep three separate variables, but they belong together. Go's tool for grouping related data is the struct. Go has no classes; structs plus methods cover the same ground in a simpler way.
A struct type lists named fields, each with a type:
Create values with a struct literal. Naming the fields is clearer and keeps working if you add fields later. Fields you leave out get their zero value.
fmt.Printf("%+v\n", p) prints a struct with its field names, which is great for debugging:
{Name:Rin Health:100 Level:2}.
Structs are values. Assigning one to another variable, or passing it to a function, copies every field.
A method is a function with a receiver, written in parentheses before the name. The receiver is the value the method is called on.
Because arguments are copies, a method with a plain value receiver cannot change the original. To modify it, use a pointer receiver, written :
2 exercises to try what you just read.
*PlayerA pointer holds the address of a value rather than a copy of it. &p takes the address,
and through a pointer you can reach and change the original. Go lets you write p.Health on a
pointer without any special arrow syntax.
A good rule: if any method needs a pointer receiver, give all the type's methods pointer receivers, so the type behaves consistently.
Go has no special constructors. By convention you write a function named NewThing that
sets up a valid value, often returning a pointer:
Structs combine naturally with slices and maps. A []Player is a team; a
map[string]*Player lets you find a player by name and update them in place.
When you loop with for _, p := range team, p is a copy. To change the elements, index
into the slice: team[i].Level++.
A struct can include another type without a field name. The inner type's fields and methods are then reachable directly from the outer one. This is how Go reuses behaviour without inheritance:
Define a struct Rect with Width and Height fields (int) and two methods: Area() int
and Perimeter() int. Also add IsSquare() bool. Read rectangles, one per line as
width height, until input ends, and for each print:
Sample input:
Sample output:
Define a struct Bank with an Owner string and a Coins int, plus:
Deposit(n int) adds n coins (pointer receiver).Spend(n int) bool removes n coins and returns true, or returns false and changes
nothing if there are not enough coins (pointer receiver).String() string returns <owner> has <coins> coins.The first input line is the owner's name. Each following line is a command: deposit N or
spend N. After each spend that fails, print cannot spend N. At the end, print the
bank's String(). The starter splits each command with fmt.Sscan, which works like
fmt.Scan but reads from a string.
Sample input:
Sample output:
type Player struct {
Name string
Health int
Level int
}p := Player{Name: "Rin", Health: 100}
fmt.Println(p.Name, p.Level) // Rin 0
p.Level = 2 // fields are read and set with a dotfunc (p Player) Describe() string {
return fmt.Sprintf("%s (level %d)", p.Name, p.Level)
}
fmt.Println(p.Describe()) // Rin (level 2)func (p *Player) TakeDamage(n int) {
p.Health -= n
if p.Health < 0 {
p.Health = 0
}
}
p.TakeDamage(30) // Go passes &p for you automatically
fmt.Println(p.Health) // 70func NewPlayer(name string) *Player {
return &Player{Name: name, Health: 100, Level: 1}
}type Boss struct {
Player // embedded
Phase int
}
b := Boss{Player: Player{Name: "Hydra", Health: 500}}
fmt.Println(b.Name, b.Describe())<w>x<h> area=<area> perimeter=<perimeter> square=<true|false>3 4
5 53x4 area=12 perimeter=14 square=false
5x5 area=25 perimeter=20 square=trueMilo
deposit 10
spend 4
spend 9
deposit 3cannot spend 9
Milo has 9 coins