golang

4 thoughts
last posted Aug. 19, 2014, 3:01 p.m.

1 earlier thought

1

Methods in Go can have a struct receiver or a pointer receiver. For example, given a Person struct:

type Person struct { name string }

You could implement a Hello() method as either

func (p Person) Hello() string { return "Hello " + p.name }

or

func (p *Person) Hello() string { return "Hello " + p.name }

The difference between the two is what p is: in the case of the former, p is a copy of the Person struct, and any changes you make won't be reflected in the caller.

In the case of the latter -- where p is a pointer receiver, *Person -- p is mutable, and its contents can be changed. Another difference is that when you use a pointer receiver the contents of p don't need to be copied before executing the Hello() method. This can be really important for large structs.

2 later thoughts