Skip to content
Codewilds

Lesson 23 of 38 · Structs & Methods

Go Methods: Value and Pointer Receivers

medium20 XP4 min read

Functions that work on a type often belong to that type. Instead of writing Area(r), Go lets you declare a method and call r.Area(). Methods keep behaviour right next to the data it works on, and calls read like sentences: wallet.Deposit(50), door.Open().

Every Go method comes with one decision: should it receive a copy of the value, or a pointer to it? This lesson is all about that choice.

Declaring a method

A method is a function with a special first parameter, the receiver, written in parentheses before the method name:

type Circle struct {
	Radius float64
}

// Area is a method with the receiver c of type Circle.
func (c Circle) Area() float64 {
	return 3.14 * c.Radius * c.Radius
}

func (c Circle) Diameter() float64 {
	return 2 * c.Radius
}

func main() {
	c := Circle{Radius: 2}
	fmt.Println(c.Area(), c.Diameter()) // 12.56 4
}

Inside the method, the receiver is an ordinary variable. By convention it gets a short name — one or two letters derived from the type, like c for Circle — never this or self.

Value receivers vs pointer receivers

With a value receiver (c Counter) the method gets a copy, exactly like any other parameter. With a pointer receiver (c *Counter) it gets a pointer and can change the original:

type Counter struct {
	n int
}

// IncCopy has a value receiver: it increments a copy.
func (c Counter) IncCopy() {
	c.n++
}

// Inc has a pointer receiver: it increments the original.
func (c *Counter) Inc() {
	c.n++
}

func main() {
	var c Counter
	c.IncCopy() // no effect on c
	c.Inc()
	c.Inc()
	fmt.Println(c.n) // 2
}

Choose a pointer receiver when the method must modify the receiver, or when the type is large and copying it on every call would be wasteful. Value receivers suit small types whose methods only read, like Circle.

Go takes the address for you

Notice that c.Inc() compiled although c is a Counter, not a *Counter. When the receiver is an addressable variable, Go rewrites the call as (&c).Inc(). The reverse works too: if p is a *Counter, p.IncCopy() means (*p).IncCopy(). So you can call any method on a value or on a pointer — the receiver type only decides whether the method sees the original or a copy.

The automatic & needs a variable to point to. A map element or a temporary value isn't addressable, so m["a"].Inc() and Counter{}.Inc() fail with cannot call pointer method Inc on Counter.

The consistency rule: if any method of a type needs a pointer receiver, give all of its methods pointer receivers, even the read-only ones. Then every method works on the same shared value, and the type behaves predictably with interfaces (next chapter). The Counter above mixes both kinds only to show the difference.

Methods on any named type

Methods aren't limited to structs. Any named type declared in your package can have them — even a number:

type Celsius float64

func (c Celsius) Fahrenheit() float64 {
	return float64(c)*9/5 + 32
}

func (c Celsius) String() string {
	return fmt.Sprintf("%.1f°C", float64(c))
}

func main() {
	temp := Celsius(21.5)
	fmt.Println(temp.Fahrenheit())
	fmt.Println(temp)
}
70.7
21.5°C

The second line is special: fmt.Println(temp) called the String() method by itself. A type with a String() string method decides how fmt prints it, because it satisfies the fmt.Stringer interface — the topic of the next chapter.

You can't add methods to built-in types or to types from other packages (func (n int) Double() is a compile error), so declare your own type, such as type Score int, instead.

Methods guard the rules

A lowercase field such as balance is unexported: code outside the package can't touch it. Nobody can set a wallet's balance to -1000 directly — they must go through methods like Deposit and Withdraw, which validate every change.

Common mistakes

  • A value receiver on a method that modifies: the changes go to a copy and vanish when the method returns. There's no error, just a silent bug.
  • Mixing receiver kinds on one type: when one method needs a pointer receiver, give all of them one.
  • Calling a pointer method on a map element: m["a"].Inc() doesn't compile. Store pointers in the map, or copy the value out, change it and store it back.
  • Recursion in String(): fmt.Sprintf("%v", c) inside String() calls String() again, forever. Convert first: float64(c).

Assignment

You'll write methods for two types with different jobs.

Rect (Width and Height, both float64) is a small value that never changes in place — operations return a new Rect — so all its methods use value receivers:

  1. Area() float64 returns Width * Height.
  2. Perimeter() float64 returns 2 * (Width + Height).
  3. Scaled(factor float64) Rect returns a new Rect with both sides multiplied by factor. The original stays unchanged.

Wallet has an Owner and an unexported balance. Its methods change it, so all of them use pointer receivers. Careful: one of them has the wrong receiver in the starter — find it and fix it.

  1. Deposit(amount int) adds amount to the balance. Zero and negative amounts are ignored.
  2. Withdraw(amount int) bool subtracts amount and returns true. If amount is zero or negative, or larger than the balance, it returns false and the balance stays unchanged.
  3. Balance() int returns the current balance.
r := Rect{Width: 3, Height: 4}
fmt.Println(r.Area(), r.Perimeter(), r.Scaled(2)) // 12 14 {6 8}

w := Wallet{Owner: "Ada"}
w.Deposit(50)
fmt.Println(w.Withdraw(80), w.Withdraw(20), w.Balance()) // false true 30

Premium lesson

Unlock the full Learn Go course

  • All 38 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Keep learning

Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.

Lesson last updated on .

Write code ↓
Go+20 XP

Lesson 23 is part of the full course. The first 9 lessons are free.

Premium lesson

Unlock the full Learn Go course

  • All 38 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.