Methods and receivers
A method is a function with a receiver. The method set of a value and of a pointer differ.
A method is a function that names a receiver before the name:
type Box struct {
W, H int
}
func (b Box) Area() int {
return b.W * b.H
}
A value receiver is a copy. The method will not change the original struct. A pointer receiver can change fields and does not copy a large struct:
func (b *Box) Scale(f int) {
b.W *= f
b.H *= f
}
The method-set rule matters for interfaces. The type Box has the methods with receiver Box. The type *Box has those and also the methods with receiver *Box. So a value of type Box cannot be put into an interface that requires a method with a pointer receiver: the value does not have that method. A pointer can be put into such an interface. If at least one method of the type changes the receiver, the other methods of that type take a pointer receiver too. Mixing styles on one type confuses the reader about which method copies and which does not.
The call b.Scale(2), when b is a variable that holds a value, is rewritten by the compiler as (&b).Scale(2), if b is addressable. This is sugar, and it does not work for a temporary value that cannot be addressed. Do not count on the sugar in an API: if a method requires a pointer, let the signatures around it work with a pointer too.
A method does not have to live in the same file, but it must live in the same package as the type. You cannot add a method to string or to a type from another package. For that you introduce your own named type: type Money int64.
Practice
The method set
Boxhas a methodScalewith receiver*Box. Can a value of typeBox(not a pointer) be stored in an interface whose only method is that one?- Yes, the compiler will take the address itself
- No, the value does not implement a method with a pointer receiver
- Yes, if the struct is small
- No, interfaces accept only interfaces
Area
Declare
Boxwith fieldsWandHof typeint. Write a methodArea() intwith a value receiver: the product of the sides.One receiver style
Some methods of a type change fields and are declared on a pointer. How should the other methods of the same type be declared?
- On a pointer as well
- Necessarily by value, so there is a difference
- With no receiver at all, as ordinary functions
- On a pointer only if the struct is larger than 64 bytes, otherwise however it turns out