Andrew's Digital Garden

Methods in Go

Functions tied to a type, are known as methods. Practically, adding a receiver to a method turns it into a function. A data type with a set of methods describes an object that has both a state (that is defined by the data) and a behavior (that is defined by the methods).

Encapsulation - methods help with encapsulation, as they can grant controlled access to unexported struct fields. (Remember that lower-case identifiers are unexported.) For example, a method could make a value read-only, or it could verify the input when updating a value.

Polymorphism - different types can have methods of the same name and signature, like the Person and Actor types in this example.

var p Person var a Actor p.Age() // no conflict with a.Age() a.Age() // no conflict with p.Age() // Not possible if Age(p Person) and // Age(a Actor) were plain functions

A function can receive an abstract type that represents different types, and the function then can call the 'shared' method regardless the receiver's type.

func GetAge (h HumanBeing) { // HumanBeing "knows" method Age() h.Age() } GetAge(p) // Person implements Age(), so GetAge accepts p GetAge(a) // Actor implements Age(), so GetAge accepts a

This abstract type is called an "interface". TODO - link

Inheritance - Go uses embedding rather than inheritence. When a struct is embedded into another struct, the outer struct also has access to the methods of the embedded struct. The mechanism is the same as with the fields of the embedded struct. That is, the outer struct can access the methods of the inner struct as if they were methods of the outer struct. [[20200720142621-go-struct-embedding]]

[[20200704153829-go-receivers]] [[20200720140304 -go-types]]

[[go]]

Methods in Go