×

go · level 2 · unit 2 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.