Start learning free

LESSON 641 OF 671 · OBJECT-ORIENTED PROGRAMMING

Interfaces in Go

Lesson

TL ; DR:

An interface is a pure contract — a list of methods that a type promises to implement, with no shared data and no shared code. Unlike inheritance ("is a"), interfaces express "can do".


// Go uses an interface type listing the required methods:
type Speaker interface {
    speak()
}

type Dog struct{}

func (d Dog) speak() {
    fmt.Println("Woof")
}


Full lesson:

An interface defines what a type can do, not how it does it or what it is. A Truck, a Robot, and a Drone aren't the same kind of thing — but they can all Move(). You'd put Move() in a Movable interface and have each one implement it.

Interface vs abstract class

Abstract classInterface
Has fieldsYesUsually no
Has method bodiesYes (some)No (or default impls only)
Multiple "inheritance"Usually noYes — a class can implement many interfaces
Models"is a""can do"

A class inherits from at most one parent class but can implement many interfaces. That's why interfaces are the right tool for cross-cutting capabilities like Comparable, Serializable, Iterable, etc.

The language landscape

  • Go — an interface type lists method signatures. A type implements it implicitly just by having those methods (there is no implements keyword), and one type can satisfy many interfaces.
  • C# / Java — first-class interface keyword. C# uses : for both inheritance and implementation; Java uses extends for inheritance and implements for interfaces.
  • Python — no separate interface; abstract base classes (ABCs) with all-abstract methods serve the same role.
  • JavaScript — no interface keyword in plain JS (TypeScript has it). The convention is a stub class.
  • C++ — a class with only pure-virtual methods is an interface. Multiple inheritance lets a class implement several.

Your task

The Speaker interface is already declared. Create a Dog struct that implements it, with a speak() method that prints "Woof".

Expected output:

Woof
STEP 1 OF 5
    Ctrl + Enter to check