Tour of go, function vs method
Generally speaking, there are two way to manipulate a typed variable
- function
- method
type vertex struct { a int b int }
-
function with value parameter
func f(v vertex) int { return v.a; }
a copy of v is passed to function, and only a value is allowed when calling the function
-
function with pointer parameter
func f(v *vertex) int { return v.a }
pointer (reference) is passed to function
only pointer is allowed when calling this functionv := vertex{3, 4} f(&v) // OK f(v) // compile error
this is easy to understand if you know about C, but things get bit tricky dealing with methods
A method
is a kind of special function bind to a specific type
, with the data type called receiver
. Just treat that receiver as a special parameter. So you can call this method by writing receiver.method(...parameters)
, common in many Object-Oriented languages
-
method with value receiver
Syntax:
func (v vertex) f(s int) { v.a = v.a * s }
a copy of v is passed to method
both value and pointer is allowed when calling the method,
and nothing in origin data will changeExample:
v := vertex{1,2} v.f(2) // OK fmt.Println(v) // {1 2} p := &v p.f(2) // OK, equal to "(*p).f()" fmt.Println(p) {1 2}
-
method with pointer receiver
Syntax:func (v *vertex) f(s int) { v.a = v.a * s }
pointer of v is passed to method
both value and pointer is allowed when calling this method,
and both case may change the content of the original dataExample:
v := vertex{1,2} v.f(2) // OK equal to "(&v).f(2) fmt.Println(v) // {2 4} p := &v p.f(2) // OK fmt.Println(p) {4 8}
Another Note about interface
if a type implement an interface, calling the implemented method is not flexible any more, only the type (pointer receiver or value receiver) is allowed when calling.