GO / CHAPTER 06

Structs, methods, and small interfaces

Intermediate

Design behavior around a record and the methods a consumer needs.

By the end of this chapter

  • Distinguish value and pointer receivers
  • Define a focused interface
  • Recognize implicit interface satisfaction

The idea

Enter with structs and function calls understood. A struct groups named fields into one value. A method is a function associated with a receiver type. A value receiver works with a copy of the receiver; a pointer receiver can modify the original record through its pointer. Choose the receiver deliberately rather than expecting every method call to mutate its caller’s variable.

An interface describes required methods. A type satisfies it by having the appropriate method set, without an explicit implements declaration. Keep interfaces focused on what a consumer needs, such as a single Size method, instead of collecting unrelated behavior. Pointer and value method sets differ, so passing a value and passing its address are not interchangeable in every interface assignment. This chapter uses a value method for read-only behavior.

Go example
package main
import "fmt"
type Box struct { Count int }
func (b *Box) Add(n int){b.Count+=n}
func main(){b:=Box{Count:2}; b.Add(3); fmt.Println(b.Count)}
Result
5

The pointer receiver refers to b’s original storage, so Add changes its Count field from two to five.

Try it yourself

Define an interface with a Size() int method and a record type that satisfies it.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which receiver is appropriate for incrementing the original Counter.N field?