6

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
}

2 Answers 2

4

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...)
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.