Golang methods

From wikinotes
Revision as of 15:42, 6 June 2022 by Will (talk | contribs) (→‎Local Types)
(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


Adding Methods

Basics

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

Pointers as self

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

Method Overloading

Not supported in go.