Pointers in Go
Go has pointers but no pointer arithmetic: they exist to share and to mutate.
type Counter struct {
n int
}
func (c *Counter) Add(delta int) { c.n += delta }
func (c Counter) Value() int { return c.n }
func pointers() (int, int, bool) {
counter := Counter{}
counter.Add(3) // Go takes the address for you
byPointer := &counter
byPointer.Add(4)
fresh := new(int)
*fresh = 7
var nothing *Counter
return counter.Value(), *fresh, nothing == nil
}
How it works
&xtakes an address,*preads through it.new(T)allocates a zero T and returns its pointer.- A nil pointer dereference panics, so check when it can be nil.
Keywords and builtins used here
boolfuncintnewreturnstructtypevar
The run, in numbers
- Lines
- 19
- Characters to type
- 372
- Tokens
- 102
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 76 seconds.
Step 5 of 5 in Variables & types, step 5 of 30 in Language basics.