Golang methods

From wikinotes
Revision as of 14:19, 6 June 2022 by Will (talk | contribs)

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


Adding Methods

type Rectangle struct {
    width int
    height int
}

func (a Rectangle) Area() int {
    return a.width * a.height
}

func main() {
    rect := Rectangle{width: 10, height: 10}
    fmt.Println(rect.Area() == 100)
}

Keep in mind that go parameters are value types and will contain copies of your object.
If working with large objects, it may be more efficient to refer to the object as a pointer.

type Rectangle struct {
    width int
    height int
}

func (a *Rectangle) Area() int {
    // manually de-reference pointer 'a' to get it's value
    return (*a).width * (*a).height
}

func (a *Rectangle) Perimeter() int {
    // go knows you are working with a pointer, you can skip the '(*a)'
    return (a.width * 2) + (a.height * 2)
}

func main() {
    rect := Rectangle{5, 5}
    fmt.Println(rect.Area())
}

Local Types

You can also create local wrapper types for other types,
which lets you add methods, only in a specific localized scope

type Int int

func (i Int) Double() Int {
    return i * 2
}

func main() {
    five := Int(5)
    fmt.Println(five.Double() == 10)
}

Basics

Methods let you bind functions to existing types.

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 main() {
    animal := Animal{name: "foo", age: 123}
    animal.meow()
    animal.pounce()
}