Pointers vs. Values

methods can be defined for any named type (except a pointer or an interface)

value receiver

  1. type ByteSlice []byte
  2. func (slice ByteSlice) Append(data []byte) []byte {
  3. // ...
  4. }

pointer receiver

  1. func (p *ByteSlice) Append(data []byte) {
  2. slice := *p
  3. // Body as above, without the return.
  4. *p = slice
  5. }

The rule about pointers vs. values for receivers is that

  • value methods can be invoked on pointers and values,
  • but pointer methods can only be invoked on pointers.