go · level 2 · unit 2 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
means nothing there, and constructors build things well.
A pointer that points at no box at all is nil. var best *Pet starts as nil, because nothing has been pointed at yet, and you can check with if best == nil. Reach through a nil pointer, as in best.Name, and the program panics.
&Pet{Name: "Rex"} builds a struct and hands back its address in one go. That is handy in a : a function such as NewAccount that builds a value with good starting settings and returns a pointer to it.
A constructor keeps the rules in one place. If every new account must start with a £5 welcome bonus, put that inside NewAccount, and nobody can forget it.
package main
import "fmt"
type Account struct {
Owner string
Balance int
}
func NewAccount(owner string) *Account {
return &Account{Owner: owner, Balance: 5}
}
func main() {
var empty *Account
fmt.Println(empty == nil)
acc := NewAccount("Leo")
fmt.Println(acc.Owner, acc.Balance, acc == nil)
} A map that was never made is nil too, which is why storing anything in one panics.
guess first
Nobody has won yet. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
type Pet struct {
Name string
}
func main() {
var winner *Pet
fmt.Println("And the winner is...")
fmt.Println(winner.Name)
}
your turn
Your turn. Set up a new player.
Choose how many lives every new player starts with, then make a player with your own name. Score is left out, so it starts at its zero value.
output
press run to see what happens
fix it
Goldie is missing and the program crashes. Fix it!
output
press run to see what happens
- The panic comes from line 10. What does a missing key give back in a map of pointers?
- A missing key gives the zero value, and for a pointer that is
nil. Check for it first. - Wrap line 10 in if found == nil { print No pet called Goldie } else { line 10 }, then run.
nailed it
you can build things safely now. :D
nilmeans a pointer points at nothing.- Reaching through a nil pointer panics, so check with
== nilfirst. - A constructor builds a value with good starting settings.
new words in your collection
- nil
- constructor
This lesson isn’t saved. A free account remembers every lesson you finish.