Thursday, 19 May 2016

Methods with Pointer Receiver in Go

Go does not have classes. However, you can define methods on types.
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.
You can only declare a method with a receiver whose type is defined in the same package as the method.

Methods with pointer receivers can modify the value to which the receiver points (as Scaledoes here). Since methods often need to modify their receiver, pointer receivers are more common than value receivers. Functions with a pointer argument must take a pointer &v.
There are two reasons to use a pointer receiver.
The first is so that the method can modify the value that its receiver points to.
The second is to avoid copying the value on each method call. This can be more efficient if the receiver is a large struct, for example.
With a value receiver, the method operates on a copy of the original Vertex value. The method must have a pointer receiver to change the Vertex value declared in the main function.

For the statement v.Scale(10), even though v is a value and not a pointer, the method with the pointer receiver is called automatically. That is, as a convenience, Go interprets the statement v.Scale(10) as (&v).Scale(10) since the Scalemethod has a pointer receiver.


func (v *Vertex) Scale(f float64) {
       v.X = v.X * f
       v.Y = v.Y * f
}

func Scale(v *Vertex, f float64) {
       v.X = v.X * f
       v.Y = v.Y * f
}
func main() { v := Vertex{3, 4} v.Scale(10)//&v.Scale(10) or Scale(&v,10) fmt.Println(v.X, v.Y) }

No comments:

Post a Comment