Understand the contract

A method is a function with a receiver parameter. Attach it to a named type to express behavior associated with that type. A value receiver works on a copy; a pointer receiver can modify the original value. Choose deliberately, especially when the type contains mutable state or must not be copied.

The Counter type keeps its field unexported and exposes Add and Value. Add has a *Counter receiver because it mutates n. Value also uses *Counter to keep the method set consistent. For an addressable variable, Go can automatically take its address when calling an appropriate pointer method.

Work through the example

The zero value of Counter is usable, so main needs no constructor. Adding three and reading Value prints three. A constructor becomes useful when a valid object requires configuration or resources, but adding one by habit can make a naturally useful zero value harder to use.

package main

import "fmt"

type Counter struct { n int }

func (c *Counter) Add(delta int) { c.n += delta }
func (c *Counter) Value() int { return c.n }

func main() {
    var counter Counter
    counter.Add(3)
    fmt.Println(counter.Value())
}

Watch this boundary

Automatic address-taking for calls does not make Counter and *Counter interchangeable when satisfying interfaces. Their method sets differ. Also avoid copying structs containing an active mutex. The later interface and mutex lessons connect these rules to substitutability and concurrent state.

Practice with a changed input

Change Add to a value receiver and predict the printed result. Restore the pointer receiver, then add a Reset method and define whether negative increments are allowed.

References & further reading

Need help with your Go backend?

I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.

Explore Go consulting services