Skip to content

Go Methods

In Go, a method is simply a function with a special "receiver" argument. This allows you to "attach" behavior to your custom types (usually structs).

Defining a Method

package main

import "fmt"

type rect struct {
    width, height int
}

// This 'area' method has a receiver of type 'rect'
func (r rect) area() int {
    return r.width * r.height
}

func main() {
    r := rect{width: 10, height: 5}

    // Call the method using the dot operator
    fmt.Println("Area:", r.area())
}

Pointer vs. Value Receivers

There are two ways to define methods:

  1. Value Receiver (r rect): The method gets a copy of the struct. It cannot change the original data.
  2. Pointer Receiver (r *rect): The method gets a pointer to the struct. It can modify the original data.
package main

import "fmt"

type counter struct {
    val int
}

// Value receiver: won't change the original counter
func (c counter) incrementCopy() {
    c.val++
}

// Pointer receiver: WILL change the original counter
func (c *counter) incrementReal() {
    c.val++
}

func main() {
    c := counter{val: 0}

    c.incrementCopy()
    fmt.Println(c.val) // 0

    c.incrementReal()
    fmt.Println(c.val) // 1
}

Why use Methods?

  • Encapsulation: Group logic together with the data it belongs to.
  • Interfaces: To satisfy an interface, a type must implement specific methods.
  • Clean Syntax: It often feels more natural to write user.Save() than SaveUser(user).

Important Rule

Go automatically handles conversion between values and pointers for method calls. If you call a pointer-receiver method on a value, Go will automatically pass the address (&).