A method is a function tied to a type, usually a struct but it works with any type.
This is similar to classes in languages like Java or C++.
Basics of methods:
https://codeeval.dev/gist/6c730ba2eae313952f1e5409e0fa7321
The instance on which the method operates is called a receiver.
In the above example method PrintFullName
takes a receiver p
whose type is *Person
.
People coming from other languages are tempted to name the receiver this
(mimicking C++) or self
(mimicking Python). That is bad style in Go.
In Go, the rule for naming receiver is:
Method receiver can be either a value or a pointer.
As a convenience, the Go allows calling a pointer receiver on a value and calling a value receiver on a pointer:
https://codeeval.dev/gist/f225654f7c0177efd2871978f988a06d
A value receiver is called on a copy of a value:
https://codeeval.dev/gist/83c99d94cbd25e6fd6ea184a2432a4c8
You can see above the consequences of calling value receiver on a copy of a value:
f
receiver is different that the address of fv
value. This indicates it's a different value i.e. f
is a copy of fv
that Go compiler created impliciltyf
inside Print
value receiver doesn't change the fv
value