Go

Methods and Receivers

admin by @admin ADMIN
Jun 15, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Methods are functions with a receiver argument. Use pointer receivers when you mutate, when the struct is large, OR for consistency (mixing pointer + value receivers on the same type is a common bug source).
Go
Raw
package main

import "fmt"

type Counter struct {
    count int
    name  string
}

// Pointer receiver — needed to mutate
func (c *Counter) Inc() {
    c.count++
}

// Value receiver — fine when you only read
func (c Counter) String() string {
    return fmt.Sprintf("%s: %d", c.name, c.count)
}

// Convention: be consistent — if any method needs pointer receiver,
// make ALL methods pointer receivers.

func main() {
    c := Counter{name: "visits"}
    c.Inc()
    c.Inc()
    c.Inc()
    fmt.Println(c)                                  // visits: 3 (uses String())

    // Pointer methods can be called on values; Go auto-addresses
    var p Counter
    p.Inc()                                          // sugar for (&p).Inc()
    fmt.Println(p)
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.