2018-09-20 Go Learning Notes

Go’s pointers and values behave differently when used as receivers and parameters

Methods and pointer indirection When comparing the first two programs, you might notice that functions with pointer parameters must accept a pointer:

var v Vertex ScaleFunc(v, 5) // Compile error! ScaleFunc(&v, 5) // OK However, methods with pointer receivers can be called with both values and pointers:

var v Vertex v.Scale(5) // OK p := &v p.Scale(10) // OK For the statement v.Scale(5), even though v is a value and not a pointer, methods with pointer receivers can still be called directly. In other words, since the Scale method has a pointer receiver, for convenience, Go interprets the statement v.Scale(5) as (&v).Scale(5).

Additionally, Go automatically interprets the . operation on pointers as (*).

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy