Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go's value method receiver vs pointer method receiver

Tags:

go

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
}
like image 757
alexdotc Avatar asked Jul 25 '14 16:07

alexdotc


People also ask

How is a pointer receiver different from a value receiver function in go?

Methods with pointer receivers can modify the value to which the receiver points (as scale does here). Since methods often need to modify their receiver, pointer receivers are more common than value receivers. With a value receiver, the scale method operates on a copy of the original Point value.

Why do T and * T have different method sets?

This distinction arises because if an interface value contains a pointer *T, a method call can obtain a value by dereferencing the pointer, but if an interface value contains a value T, there is no safe way for a method call to obtain a pointer.

What is a method receiver go?

A method is a function with a special receiver argument. The receiver appears in its own argument list between the func keyword and the method name. In this example, the Abs method has a receiver of type Vertex named v . < 1/26 > methods.go Syntax Imports.

What are Golang pointers?

Pointers in Go programming language or Golang is a variable that is used to store the memory address of another variable. Pointers in Golang is also termed as the special variables. The variables are used to store some data at a particular memory address in the system.


1 Answers

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...)
}
like image 197
JimB Avatar answered Nov 15 '22 06:11

JimB