A method
is a function with a receiver
.
The term "method
" came up with object-oriented programming.
In an OOP language (like C++ for example) you can define a "class" which encapsulates data and functions which belong together.
Those functions
inside a class
are called methods
and you need an instance of that class to call such a method.
type item struct { id string price int } func (i *item) process() (string, int) { return i.id, i.price }
receiver
Stating that function operates on an object of defined name and its type:
item
is a struct type defined.
item
is used via item.id
and item.price
.This is where the dependency injection using fx
would be made available
The type in this parameter is the thing you call the method from, much like some method A
inside some class Person
then I would need an instance of type Person
in order to call A
(assuming it's an instance method and not static).
The receiver
gets pushed onto the call stack
like other arguments
copy
of the thing you called the method from
i.id = "1"
would not persist after you return to the calling scope.Anything that expects to change the state
of the receiver
needs to use a pointer
or return the modified value (returning gives more of an immutable type paradigm if you're looking for that).
process()
is the name of the function.
(string, int)
defines multiple return values of string
and integer
types.
func (p *Point) Length() float64 { return math.Sqrt(p.x * p.x + p.y * p.y) } func (p *Point) Scale(factor float64) { p.x *= factor p.y *= factor }
Above function binds the methods Length
and Scale
, with receiver type *Point
, to the base type Point
.