Golang methods

From wikinotes
Revision as of 02:48, 6 June 2022 by Will (talk | contribs) (→‎Basics)

While Go is not an OOP language, it lets you bind methods to any type.
This is most common with structs, but any type is supported


Basics

Methods let you bind functions to existing types.

type Animal struct {
    name string
    age int
}

func (a *Animal) meow() {
    // a reference to 'a' is passed to this method
    // (field assignments change original instance)
    fmt.Println((*a).name + " says: meooow")
}

func (a Animal) pounce() {
    // a copy of 'a' is created in memory, and passed to this method
    // (field assignments have no effect outside of this object)
    fmt.Println(a.name + " crouches and pounces")
}

func main() {
    animal := Animal{name: "foo", age: 123}
    animal.meow()
    animal.pounce()
}