Structs, Methods and Interfaces: Value or Pointer Receivers
Learn Go structs, methods with value and pointer receivers, embedding, the Stringer interface and your own interfaces, and see in real output which receiver changes the original.
In this lesson you will
- Define structs and methods
- Choose value or pointer receivers
- Use interfaces implicitly
- Sort structs
About 28 minutes
A parcel with behaviour
Mei’s parcel has a tracking code, a weight, a region and a status, and she wants it to know how to describe itself, how to mark itself delivered and how to compute its price. Go has no classes. It has structs, which hold data, and methods, which are functions attached to a type. Interfaces then describe behaviour, and a type satisfies an interface automatically, just by having the right methods, with no keyword to declare it.
A method is declared with a receiver before its name: func (p Parcel) Describe() string. A value receiver works on a copy, so it cannot change the original. A pointer receiver, func (p *Parcel) Deliver(), works on the original and can change it. Use pointer receivers for methods that modify the struct, and for large structs to avoid copying, and keep the same kind for all methods of a type. An interface is a set of methods: type Carrier interface { Cost(kg float64) float64 }. Any type with that method is a Carrier, which makes it easy to write code against behaviour and to swap implementations in tests. A struct can embed another type, and the outer type then gets the embedded type’s methods, which is composition and not inheritance. If a type has a String() string method, fmt prints it with that, because it satisfies fmt.Stringer.
| Feature | Syntax | Notes |
|---|---|---|
| Struct | type Parcel struct { Code string; Kg float64 } | Fields; capitalised names are exported |
| Value receiver | func (p Parcel) Price() float64 | Works on a copy |
| Pointer receiver | func (p *Parcel) Deliver() | Can modify the original |
| Interface | type Carrier interface { Cost(float64) float64 } | Satisfied implicitly |
| Embedding | type Express struct { Van; Rush float64 } | Promotes the embedded methods |
package main
import (
"fmt"
"sort"
)
type Parcel struct {
Code string
Kg float64
Delivered bool
}
func (p Parcel) MarkDeliveredCopy() { p.Delivered = true }
func (p *Parcel) MarkDelivered() { p.Delivered = true }
func (p Parcel) String() string { return fmt.Sprintf("%s (%.1f kg, delivered=%v)", p.Code, p.Kg, p.Delivered) }
type Carrier interface {
Cost(kg float64) float64
Name() string
}
type Van struct{ PerKg float64 }
type Bike struct{}
func (v Van) Cost(kg float64) float64 { return 5 + v.PerKg*kg }
func (v Van) Name() string { return "van" }
func (Bike) Cost(kg float64) float64 { return 3 + 1.2*kg }
func (Bike) Name() string { return "bike" }
type Express struct {
Van
Rush float64
}
func (e Express) Cost(kg float64) float64 { return e.Van.Cost(kg) + e.Rush }
func (e Express) Name() string { return "express " + e.Van.Name() }
func main() {
p := Parcel{Code: "PK-1", Kg: 2.5}
p.MarkDeliveredCopy()
fmt.Println("after the value receiver: ", p)
p.MarkDelivered()
fmt.Println("after the pointer receiver:", p)
carriers := []Carrier{Van{PerKg: 0.8}, Bike{}, Express{Van: Van{PerKg: 0.8}, Rush: 4}}
for _, c := range carriers {
fmt.Printf("%-12s 2.5 kg costs %.2f\n", c.Name(), c.Cost(2.5))
}
_, isVan := carriers[0].(Van)
_, isBike := carriers[0].(Bike)
fmt.Println("first carrier is a Van:", isVan, "| is a Bike:", isBike)
ps := []Parcel{{"PK-3", 7.5, false}, {"PK-1", 2.5, true}, {"PK-2", 0.4, false}, {"PK-4", 3.0, false}}
sort.Slice(ps, func(i, j int) bool { return ps[i].Kg < ps[j].Kg })
for _, x := range ps {
fmt.Println(" ", x)
}
pp := &ps[0]
pp.Kg = 0.5
fmt.Println("changed through a pointer into the slice:", ps[0].Kg)
}
after the value receiver: PK-1 (2.5 kg, delivered=false)
after the pointer receiver: PK-1 (2.5 kg, delivered=true)
van 2.5 kg costs 7.00
bike 2.5 kg costs 6.00
express van 2.5 kg costs 11.00
first carrier is a Van: true | is a Bike: false
PK-2 (0.4 kg, delivered=false)
PK-1 (2.5 kg, delivered=true)
PK-4 (3.0 kg, delivered=false)
PK-3 (7.5 kg, delivered=false)
changed through a pointer into the slice: 0.5
The first two lines show the receivers. The method with a value receiver set Delivered on a copy, so the original still read “PK-1 (2.5 kg, delivered=false)”. The method with a pointer receiver changed the real parcel, “PK-1 (2.5 kg, delivered=true)”. Go took the address of p for you when you called a pointer method on a variable. The Stringer method controlled how fmt printed the parcel, with no extra code at the call site.
Three types satisfied the Carrier interface without declaring it: Van, Bike and Express, which embeds a Van, so it got the Van’s methods and overrode two of them. The loop priced a 2.5 kg parcel with each: the van costs 5 + 0.8 x 2.5 = 7.00, the bike 3 + 1.2 x 2.5 = 6.00 and the express van the van price plus the rush charge of 4, 11.00. The type assertions show what a Carrier really is: the first one is a Van, true, and not a Bike, false. Finally sort.Slice ordered the parcels by weight, giving the codes PK-2, PK-1, PK-4, PK-3, and a pointer into the slice changed an element in place, to 0.5.
Check by hand: 0.8 x 2.5 = 2.0, plus 5 gives 7.00. 1.2 x 2.5 = 3.0, plus 3 gives 6.00. The express van adds 4 to 7.00 for 11.00. Sorted by weight 0.4, 2.5, 3.0, 7.5, the codes are PK-2, PK-1, PK-4, PK-3.
If any method needs a pointer receiver, use pointer receivers for all of them. Mixing them confuses which methods belong to the value and which to the pointer, and affects which interfaces the type satisfies.
Functions that take small interfaces are easy to test and reuse, and functions that return concrete types give callers all the information. Keep interfaces small, often a single method.
Every program in this lesson was built and run with Go 1.24 while the course was written. Go releases twice a year, so check go.dev for the current version and release notes.
Practice
Add a Drone carrier with a flat cost and put it in the list. Write a function cheapest(carriers []Carrier, kg float64) Carrier. Add a method on Parcel that returns its price from a Carrier, and test it with a fake carrier that always costs 1.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does a pointer receiver allow?
- Faster printing
- The method can modify the original
- Private methods
- Inheritance
A value receiver works on a copy.
How does a type satisfy an interface in Go?
- By having the methods, with no declaration
- By using the implements keyword
- By inheriting
- By registering
Implicit satisfaction.
What does embedding do?
- Promotes the embedded type’s methods
- Copies the type
- Creates a class
- Hides fields
It is composition.
What does fmt use if a type has String()?
- Nothing
- The field names
- Reflection only
- That method to print the value
fmt.Stringer.
What did the type assertion carriers[0].(Van) show?
- The size
- The address
- The package
- The concrete type behind the interface
ok was true.
Summary
- Structs hold data and methods attach behaviour.
- Value receivers work on copies; pointer receivers can modify the original.
- Interfaces are satisfied implicitly.
- Embedding composes types and promotes methods.
Questions
Does Go have inheritance?
No. It has composition through embedding and polymorphism through interfaces.
What is the empty interface?
any, which every type satisfies. Use it sparingly, because it hides type information.
Why are interfaces small in Go?
A small interface, such as io.Reader with one method, is satisfied by many types and is easy to implement and to fake in tests.
