alexdotc
alexdotc

Reputation: 268

Go's value method receiver vs pointer method receiver

I've read a Tour of Go and Effective Go, http://golang.org/doc/effective_go.html#pointers_vs_values, but still have a difficult time understanding when you would define a method on a struct using a value method receiver instead of a pointer method receiver. In other words, when would this:

type ByteSlice []byte

func (slice ByteSlice) Append(data []byte) []byte {
}

be preferable over this?

func (p *ByteSlice) Append(data []byte) {
    slice := *p
    *p = slice
}

Upvotes: 6

Views: 442

Answers (2)

Mr_Pink
Mr_Pink

Reputation: 109475

Slices are one place where it's not always obvious at first. The Slice header is small, so copying it is cheap, and the underlying array is referenced via a pointer, so you can manipulate the contents of a slice with a value receiver. You can see this in the sort package, where the methods for the sortable types are defined without pointers.

The only time you need to use a pointer with a slice, is if you're going to manipulate the slice header, which means changing the length or capacity. For an Append method, you would want:

func (p *ByteSlice) Append(data []byte) {
    *p = append(*p, data...)
}

Upvotes: 4

miku
miku

Reputation: 188234

There is an FAQ entry on that matter:

First, and most important, does the method need to modify the receiver? If it does, the receiver must be a pointer.

...

Second is the consideration of efficiency. If the receiver is large, a big struct for instance, it will be much cheaper to use a pointer receiver.

Upvotes: 2

Related Questions