Skip to content
LumenaryAcademy
Practice 60 min

Structs, methods and interfaces

Data with behaviour, composition by embedding, and small interfaces satisfied without being declared.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Objects without classes

Go supports the useful parts of object-oriented programming (data bundled with the operations on it, encapsulation, polymorphism) without classes or inheritance. A struct holds data. Methods are functions attached to a type. Embedding lets one struct include another and reuse its methods. And interfaces describe behaviour: any type that has the right methods satisfies an interface automatically, without declaring that it does.

That last point is the heart of Go's design. In Java or C#, a class must announce implements Writer and must know about the interface when it is written. In Go, a type written years ago by someone else satisfies your new interface if it happens to have the right methods. This makes very small interfaces practical, and the standard library is built on them: io.Reader has one method, io.Writer has one method, and hundreds of types (files, network connections, compressors, hashers, buffers, HTTP bodies) satisfy them, so any function written for a Writer works with all of them.

The Go proverb "the bigger the interface, the weaker the abstraction" captures the style: define interfaces with one or two methods, close to where they are used, and let concrete types be plain structs.

DefinitionsH

Structs, methods and embedding

Definition— struct and method

A struct type is a sequence of named fields: type Account struct { Owner string; Balance Money }. A method is a function with a receiver, written before the name: func (a Account) Summary() string. A value receiver (a Account) gets a copy of the value; a pointer receiver (a *Account) gets the address and can modify the original. Methods can be declared on any named type defined in the same package, not only on structs.

Definition— embedding

A struct field written with a type but no name, as in type SavingsAccount struct { Account; RatePercent float64 }, is embedded. The embedded type's fields and methods are promoted: they can be used as if they belonged to the outer struct (s.Owner, s.Deposit(...)), and the outer struct still has the embedded value as a field named after its type (s.Account).

go
package main

import "fmt"

type Money int64 // in cents

func (m Money) String() string { // implements fmt.Stringer
	return fmt.Sprintf("%d.%02d", m/100, m%100)
}

type Account struct {
	Owner   string
	Balance Money
	history []string // lower case: private to this package
}

// A value receiver gets a copy: fine for methods that only read.
func (a Account) Summary() string {
	return fmt.Sprintf("%s has %v after %d transactions", a.Owner, a.Balance, len(a.history))
}

// A pointer receiver can change the struct it is called on.
func (a *Account) Deposit(amount Money) {
	a.Balance += amount
	a.history = append(a.history, fmt.Sprintf("+%v", amount))
}

// Embedding: a SavingsAccount has all of Account's fields and methods, promoted.
type SavingsAccount struct {
	Account
	RatePercent float64
}

func (s *SavingsAccount) AddInterest() {
	interest := Money(float64(s.Balance) * s.RatePercent / 100)
	s.Deposit(interest) // promoted from the embedded Account
}

func main() {
	acc := Account{Owner: "Aroha"}
	acc.Deposit(2550) // Go takes &acc automatically for a pointer method
	acc.Deposit(1000)
	fmt.Println(acc.Summary())

	s := SavingsAccount{Account: Account{Owner: "Sione", Balance: 100000}, RatePercent: 2.5}
	s.AddInterest()
	fmt.Println(s.Summary(), "| owner:", s.Owner)

	p := &s.Account
	p.Deposit(1) // methods and fields work through pointers without extra syntax
	fmt.Println(s.Balance, p.Balance == s.Balance)

	// Structs are values: assignment copies, == compares field by field.
	type point struct{ X, Y int }
	a, b := point{1, 2}, point{1, 2}
	c := a
	c.X = 9
	fmt.Println(a == b, a, c)
	fmt.Printf("%+v\n", point{3, 4})
}
text
Aroha has 35.50 after 2 transactions
Sione has 1025.00 after 1 transactions | owner: Sione
1025.01 true
true {1 2} {9 2}
{X:3 Y:4}

Things to notice:

  • Money is a named integer type with a String method. Because it has String() string, it satisfies fmt.Stringer, and fmt uses that method whenever it prints a Money with %v or Println. Counting money in integer cents avoids floating-point rounding.
  • Composite literals create structs: Account{Owner: "Aroha"} sets one field and leaves the others at their zero values. Naming the fields is preferred over the positional form (point{1, 2}) except for tiny local types, because it keeps working when fields are added.
  • history starts with a lower-case letter, so it is invisible outside the package. Encapsulation in Go is per package, not per type.
  • acc.Deposit(2550) calls a pointer method on an addressable variable; Go inserts the & for you. Likewise p.Deposit(1) and p.Balance work through a pointer without -> or explicit dereferencing.
  • SavingsAccount embeds Account, so s.Summary(), s.Owner and s.Deposit are promoted. This is composition, not inheritance: a SavingsAccount is not an Account and can't be passed where an Account is expected; it has one. If the outer struct defines a field or method with the same name, the outer one wins, and the inner one is still reachable as s.Account.Name.
  • Structs are values: c := a copies, and == compares field by field, but only if every field is comparable; a struct containing a slice can't be compared with ==.

Example— Methods on types that aren't structs

Any named type in your package can have methods, which is often neater than a struct with one field. A temperature type can convert itself, and a named slice type can summarise itself:

go
type Celsius float64

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

type Readings []Celsius

func (r Readings) Mean() Celsius {
	var sum Celsius
	for _, c := range r {
		sum += c
	}
	return sum / Celsius(len(r))
}

Readings{21.5, 23, 19.5}.Mean().Fahrenheit() reads almost like a sentence. The standard library does this too: time.Duration is an int64 with methods such as Seconds() and String(), which is why printing 90 * time.Second shows 1m30s.

Value or pointer receiver?

Use a pointer receiver when the method changes the receiver, when the struct is large enough that copying it matters, or when the type contains something that must not be copied (a sync.Mutex, for example). Use a value receiver for small, immutable values such as Money, time.Time or a 2D point. And be consistent: if any method of a type needs a pointer receiver, the convention is to give all its methods pointer receivers.

DefinitionsH

Interfaces

Definition— interface

An interface type lists method signatures. A type satisfies the interface if it has all of those methods; no declaration is needed. A variable of interface type holds a pair: a concrete type and a value of that type. Calling a method on it calls the concrete type's method (dynamic dispatch). any (another name for interface{}) is the interface with no methods, satisfied by every type.

go
package main

import (
	"fmt"
	"math"
)

// Shipper is satisfied by any type with these two methods. No "implements" keyword.
type Shipper interface {
	Name() string
	Cost(kg float64) float64
}

type Courier struct {
	name     string
	base     float64
	perKg    float64
	maxKg    float64
	flatRate bool
}

func (c Courier) Name() string { return c.name }

func (c Courier) Cost(kg float64) float64 {
	if kg > c.maxKg {
		return math.Inf(1) // can't carry it
	}
	if c.flatRate {
		return c.base
	}
	return c.base + c.perKg*kg
}

type Bicycle struct{ Rider string }

func (b Bicycle) Name() string { return "bicycle (" + b.Rider + ")" }
func (b Bicycle) Cost(kg float64) float64 {
	if kg > 10 {
		return math.Inf(1)
	}
	return 4
}

// cheapest works with any mix of Shippers.
func cheapest(options []Shipper, kg float64) Shipper {
	var best Shipper
	for _, s := range options {
		if best == nil || s.Cost(kg) < best.Cost(kg) {
			best = s
		}
	}
	return best
}

func describe(s Shipper) string {
	// A type switch inspects the concrete type behind an interface value.
	switch v := s.(type) {
	case Bicycle:
		return "a local rider, " + v.Rider
	case Courier:
		if v.flatRate {
			return "a flat-rate courier"
		}
		return "a courier charging by weight"
	default:
		return "something else"
	}
}

func main() {
	options := []Shipper{
		Courier{name: "PostNet", base: 6, perKg: 1.2, maxKg: 30},
		Courier{name: "BoxFlat", base: 15, maxKg: 20, flatRate: true},
		Bicycle{Rider: "Thandi"},
	}
	for _, kg := range []float64{2, 12, 25} {
		best := cheapest(options, kg)
		fmt.Printf("%4.1f kg: %s at %.2f, %s\n", kg, best.Name(), best.Cost(kg), describe(best))
	}

	// A type assertion with comma-ok extracts a concrete type safely.
	if b, ok := options[2].(Bicycle); ok {
		fmt.Println("rider:", b.Rider)
	}
	_, ok := options[0].(Bicycle)
	fmt.Println("first option is a bicycle?", ok)
}
text
 2.0 kg: bicycle (Thandi) at 4.00, a local rider, Thandi
12.0 kg: BoxFlat at 15.00, a flat-rate courier
25.0 kg: PostNet at 36.00, a courier charging by weight
rider: Thandi
first option is a bicycle? false

Courier and Bicycle never mention Shipper, yet both satisfy it, so a []Shipper can hold a mix of them and cheapest works with any future shipper too. A type switch, switch v := s.(type), branches on the concrete type and gives v that type in each case. A type assertion s.(Bicycle) extracts the concrete value; the comma-ok form returns false instead of panicking when the type is wrong. Use both sparingly: if you find yourself switching on types often, a method on the interface is usually the better design.

Whether a type satisfies an interface depends on its method set. Methods with pointer receivers belong only to the pointer type. If Write has a pointer receiver, then *countingWriter is an io.Writer but countingWriter is not, and the compiler says so: "countingWriter does not implement io.Writer (method Write has pointer receiver)". That is why the next program stores &countingWriter{...}.

ComputationC

How interface values work

An interface value is two machine words. The first points to a small table describing the concrete type and, for non-empty interfaces, the addresses of its methods (the runtime calls this an itab); the second points to the data, or holds it directly when it fits. Calling s.Cost(kg) on a Shipper loads the method's address from the table and makes an indirect call. That is the whole cost of dynamic dispatch: one or two memory loads and a call the compiler usually cannot inline.

Three practical consequences follow:

  • Storing a value in an interface may allocate. If the concrete value is larger than a pointer, or its address escapes, the compiler copies it to the heap so the interface can point to it. In a hot loop, passing large structs as any can create garbage-collector work you didn't expect; profiling (lesson 9) shows it.
  • Interface comparison compares types first. Two interface values are equal if they hold the same dynamic type and equal values. Comparing interfaces whose dynamic type is not comparable (a slice, say) panics at run time, because the compiler couldn't see it coming.
  • Compilers are getting smarter. When the compiler can prove which concrete type an interface holds, it calls the method directly ("devirtualisation"), and Go's profile-guided optimisation (PGO, since Go 1.21) uses a CPU profile from production to devirtualise and inline the calls that actually matter.

You already use interfaces constantly. error is an interface with one method, Error() string. fmt.Stringer is String() string. sort.Interface has Len, Less and Swap. http.Handler (lesson 10) has a single method, ServeHTTP. Most of the standard library's flexibility comes from a dozen interfaces like these, each with one to three methods.

Worked examplesH

Small interfaces: io.Reader and io.Writer

go
package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strings"
)

// countingWriter wraps any io.Writer and counts the bytes written through it.
type countingWriter struct {
	w     io.Writer
	bytes int
}

func (c *countingWriter) Write(p []byte) (int, error) {
	n, err := c.w.Write(p)
	c.bytes += n
	return n, err
}

// report writes to any io.Writer: a file, a network connection, a buffer, stdout...
func report(w io.Writer, lines []string) {
	for i, l := range lines {
		fmt.Fprintf(w, "%d. %s\n", i+1, l)
	}
}

func main() {
	// Read from any io.Reader line by line; here, a string pretends to be a file.
	input := strings.NewReader("mangoes\npapayas\n\nguavas\n")
	scanner := bufio.NewScanner(input)
	var fruits []string
	for scanner.Scan() {
		if line := scanner.Text(); line != "" {
			fruits = append(fruits, line)
		}
	}

	cw := &countingWriter{w: os.Stdout}
	report(cw, fruits)
	fmt.Println("bytes written:", cw.bytes)

	// The same function writing into memory instead.
	var sb strings.Builder
	report(&sb, fruits[:1])
	fmt.Printf("%q\n", sb.String())

	// Interfaces compose: io.MultiWriter is itself an io.Writer.
	var copyBuf strings.Builder
	both := io.MultiWriter(os.Stdout, &copyBuf)
	fmt.Fprintln(both, "sent to two places")
	fmt.Println(len(copyBuf.String()))
}
text
1. mangoes
2. papayas
3. guavas
bytes written: 32
"1. mangoes\n"
sent to two places
19

report takes an io.Writer, an interface with one method, Write(p []byte) (n int, err error). That single decision lets it write to standard output, to an in-memory strings.Builder, through our counting wrapper, or to two destinations at once via io.MultiWriter, which is itself just another Writer. In a real program the same function could write to a file, an HTTP response or a gzip stream with no changes. On the reading side, bufio.Scanner reads lines from any io.Reader; strings.NewReader makes a string act like a file, which is handy in tests.

This is the pattern behind the Go saying "accept interfaces, return structs": parameters should ask for the smallest behaviour they need, so callers can pass anything that has it; results should be concrete types, so callers get every method.

Common misconceptionsH

The nil interface trap

An interface value is nil only when both its type and its value are nil. An interface holding a nil pointer has a type, so it is not nil. This bites most often with errors:

go
package main

import "fmt"

type ValidationError struct{ Field string }

func (e *ValidationError) Error() string { return "invalid " + e.Field }

// Wrong: returns a typed nil pointer inside a non-nil interface.
func checkWrong(name string) error {
	var err *ValidationError
	if name == "" {
		err = &ValidationError{Field: "name"}
	}
	return err // an interface holding (*ValidationError)(nil) is not nil!
}

// Right: return the untyped nil when there is no error.
func checkRight(name string) error {
	if name == "" {
		return &ValidationError{Field: "name"}
	}
	return nil
}

func main() {
	fmt.Println(checkWrong("Ife") == nil, checkRight("Ife") == nil)

	var iface any
	fmt.Println(iface == nil) // no type, no value: nil
	var p *ValidationError
	iface = p
	fmt.Println(iface == nil, fmt.Sprintf("%T", iface)) // a type but a nil value: not nil

	if err := checkRight(""); err != nil {
		fmt.Println("error:", err)
	}
}
text
false true
true
false *main.ValidationError
error: invalid name

checkWrong returns a *ValidationError variable that happens to be nil; converting it to the error interface produces a non-nil interface containing a nil pointer, and the caller's err != nil check reports a failure that never happened. The fix is the habit in checkRight: return the literal nil for "no error", and never declare a variable of a concrete error type just to return it.

Misconception

"Embedding is inheritance." An embedded type's methods are promoted, but there is no subtyping and no virtual dispatch: a method of Account called through a SavingsAccount still operates on the inner Account, and knows nothing about the outer struct's methods. For polymorphism, use interfaces.

Misconception

"I should declare interfaces next to the types that implement them, like in Java." In Go, interfaces are usually declared by the consumer, the package that needs the behaviour, and kept small. The implementing type doesn't need to know the interface exists. Declaring a large interface up front "for testability" is a common anti-pattern carried over from other languages.

Misconception

"Value receivers are faster because there are no pointers." For small structs they are often similar; for large ones, copying on every call is slower. Choose receivers for semantics first (does the method modify the value?), then for size.

ExplanationH

Designing types the Go way

Experienced Go programmers tend to follow a handful of habits when designing types:

  • Make the zero value useful. A bytes.Buffer, strings.Builder or sync.Mutex works without initialisation. When a type needs setup, provide a constructor function named NewThing that returns a ready-to-use value (often a pointer), and document what the zero value does.
  • Start concrete, extract interfaces later. Write the struct and its methods first. When a second implementation appears, or when a function only needs one or two methods of a big type, declare a small interface at the place that consumes it.
  • Embed for reuse, not for hierarchy. Embedding a sync.Mutex gives a type Lock and Unlock methods; embedding an interface in a struct lets a wrapper override one method and forward the rest. Deep embedding chains are as hard to follow as deep inheritance trees.
  • Check satisfaction at compile time when it matters. The line var _ io.Writer = (*countingWriter)(nil) costs nothing at run time and makes the build fail immediately if the type stops satisfying the interface, rather than failing somewhere far away.
  • Guard invariants with unexported fields. If a balance must never go negative, keep the field unexported and change it only through methods that check the rule. Code outside the package then cannot build an Account in an invalid state, because it cannot touch the field at all.
  • Prefer methods over type switches. A type switch has to be updated whenever a new type appears; a method on an interface is added once, by the new type itself.
Exercises

Exercises

1. Structs, methods and interfaces

CoreComputational

What does this print?

type C struct{ n int }

func (c C) IncV()  { c.n++ }
func (c *C) IncP() { c.n++ }

func main() {
	x := C{}
	x.IncV()
	x.IncP()
	x.IncP()
	fmt.Println(x.n)
}

2. Structs, methods and interfaces

CoreComputational

What does this print?

type Base struct{ Name string }

func (Base) Hello() string { return "base" }

type Derived struct {
	Base
	Name string
}

func (Derived) Hello() string { return "derived" }

func main() {
	d := Derived{Base{"b"}, "d"}
	fmt.Println(d.Name, d.Base.Name, d.Hello(), d.Base.Hello())
}

3. Structs, methods and interfaces

StretchComputational

countingWriter has func (c *countingWriter) Write(p []byte) (int, error). Which assignment compiles?

Choose one

4. Structs, methods and interfaces

CoreComputational

Why does checkWrong("Ife") == nil evaluate to false in the lesson's program, even though no error occurred?

Choose one

5. Structs, methods and interfaces

CoreComputational

Which of these struct types can be compared with ==? Choose all that apply.

Choose all that apply

6. Structs, methods and interfaces

Warm-upHuman

You are writing func SaveReport(dst ???, r Report) error. Which parameter type follows Go's usual advice?

Choose one

Further reading and resources