Golang methods

From wikinotes
Revision as of 02:47, 6 June 2022 by Will (talk | contribs) (Created page with "While Go is not an OOP language, it lets you bind methods to any type.<br> This is most common with structs, but any type is supported = Basics = <blockquote> <syntaxhighlig...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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

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()
}