HomeToolsAbout

Methods

What is a Method

A method is a function with a receiver.

  • A method declaration binds an identifier, the method name, to a method, and associates the method with the receiver's base type.

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 }

Left parameter: 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).

Receiver is an instance/copy and mutation does not persist

The receiver gets pushed onto the call stack like other arguments

  • if the receiver is a value type, then you will be working on a copy of the thing you called the method from
    • e.g. modifying 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).

Function Name

process() is the name of the function.

  • In this case, no parameter is passed to the function.

Right parameter: return type

(string, int) defines multiple return values of string and integer types.

More Examples

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.

AboutContact