Thuta Learning
IntermediateProgrammingbeginner

Methods

Relax. We'll talk through this in plain words — no textbook voice.

Method is a function tied to a type. Storing data in a struct and putting behavior in methods lets you keep your code more organized.

go
package main

import "fmt"

type Rectangle struct {
    Width  int
    Height int
}

func (r Rectangle) Area() int {
    return r.Width * r.Height
}

func main() {
    rect := Rectangle{Width: 10, Height: 5}
    fmt.Println("area:", rect.Area())
}

func (r Rectangle) Area(), (r Rectangle) is called the receiver — which is why you can call rect.Area() in an object-style way.

You should see
area: 50

Info

A method can take its receiver either as a value copy or as a pointer receiver. If you want to modify the underlying data, consider using a pointer receiver.

Easy traps

  • If a method name starts with lowercase, it can't be called from outside the package. When designing a library or API, choose your naming carefully.
Methods | Thuta Learning