← Fundamentals
Fundamentals

Interfaces, traits, and type classes

What does it mean to satisfy a contract?

A contract describes the operations a consumer expects from a value.

Outcome

Say what makes a type satisfy a contract in each language, spot an implementation that is not connected, handle an implementation that may be missing, and connect a custom equality to the protocol a container actually calls.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Interface
A contract for supported operations, and in TypeScript potentially data properties, that different types can satisfy.
Trait
Rust’s contract, implemented explicitly with impl Trait for Type.
Structural typing
Fitting a type by its shape, whatever it was declared as.
Nominal typing
Fitting a type only by an explicit declaration, such as an impl or a base class.
Default method
A method a contract provides, used unless a type supplies its own.

Separate the consumer from its implementations

An interface or trait names a set of operations that a consumer can use without knowing every concrete type. An implementation supplies those operations for a particular type. The signatures describe how to call them; their intended meaning still needs to be kept by the implementation.

A Go interface describes a method set. A concrete type satisfies it implicitly when its method set contains the required methods. Value and pointer types can have different method sets, so inspect the exact value passed to a consumer.

01Satisfying a contract

Structure, explicit implementation or a virtual base

A hotel is connecting several charge providers to one bill. The billing code must call the intended price or discount implementation, keep a bill usable when a coupon is absent, and reconcile room occupancy separately from booking revenue. Which contract does each consumer actually check?

The bill starts with two charge providers: a room stay and a tour. Follow the common price consumer and predict the two amounts including its fee.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import "fmt"

type Priced interface {
	Price() int
}

type Room struct {
	Nights int
}

func (r Room) Price() int {
	return r.Nights * 40
}

type Tour int

func (t Tour) Price() int {
	return int(t)
}

func bill(item Priced) int {
	return item.Price() + 5
}

func main() {
	fmt.Println(bill(Room{Nights: 3}), bill(Tour(7)))
}
What is printed?
Go · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
go run main.go

Use the setup from the first reading for your language.

02Satisfied by accident

A method with the right name may not keep the promise

A provider adapter is wired to the same billing contract, but its price method reports a thermometer reading. Use this reduced probe to check what the type system verifies before trusting an adapter’s meaning.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import "fmt"

type Priced interface {
	Price() int
}

type Thermometer struct{}

func (Thermometer) Price() int {
	return 21
}

func main() {
	var item Priced = Thermometer{}

	fmt.Println(item.Price())
}
What is printed?

03No implementation

An implementation that may be missing must be checked

The bill can accept a code that the hotel no longer recognizes. Before subtracting a discount, inspect the value returned for an absent coupon and predict how this caller handles it.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import "fmt"

type Discounter interface {
	Discount() int
}

type Coupon struct {
	Amount int
}

func (c *Coupon) Discount() int {
	return c.Amount
}

func lookup(code string) *Coupon {
	if code == "SAVE10" {
		return &Coupon{Amount: 10}
	}

	return nil
}

func main() {
	var coupon Discounter = lookup("NONE")

	fmt.Println(coupon == nil, coupon != nil)
}
What is printed?
Loading A typed nil still supplies a dynamic type…

04Repair the hotel bill

Discounts, coupons, then distinct rooms

The hotel billing utilities need three repairs. First apply the room discount. Then accept only coupons that exist. Finally count each booked room once.

Each file contains its imports, reader and complete caller.

Repair the hotel bill

Apply each room discount, preserve valid bills without coupons, then count numeric room identities while retaining revenue from every booking.

  1. easy · F-IFACE-V4-1 Apply the room discount
  2. medium · F-IFACE-V4-2 Accept only real coupons
  3. hard · F-IFACE-V4-3 Count each room once
Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.