Skip to content

Module 1: Interfaces (The Silent Contract)

📚 Module 1: Interfaces

Course ID: GO-112
Subject: The Silent Contract

In other languages, you must explicitly say: “This class implements this interface.” In Go, you don’t. If a struct has the right methods, it automatically follows the interface.


🏗️ Step 1: Structural Typing

🧩 The Analogy: The Duck Test

  • If it looks like a duck.
  • If it walks like a duck.
  • If it quacks like a duck.
  • Then it IS a duck.

In Go, an Interface is just a set of behaviors (methods).


🏗️ Step 2: The Contract

🧩 The Analogy: The Power Plug

  • A wall outlet is an Interface.
  • It doesn’t care if you plug in a TV or a Toaster.
  • It only cares that you have two prongs of a specific shape.

In Go:

type Shaper interface {
    Area() float64
}

type Square struct { Side float64 }
func (s Square) Area() float64 { return s.Side * s.Side }

// Square automatically "implements" Shaper because it has an Area() method!

🏗️ Step 3: Why do we use them?

  1. Decoupling: You can write a function that calculates the total area of a list of Shaper objects. You don’t need to know if they are Squares, Circles, or Triangles.
  2. Mocking: In testing, you can create a “Fake” object that follows the same interface as your Database to test your code quickly (Module 7).

🥅 Module 1 Review

  1. Interface: A set of method signatures.
  2. Implicit: No keyword required to follow an interface.
  3. Flexibility: Allowing different types to be treated the same way.

:::tip Senior Tip Keep your interfaces small. Go’s standard library is built on tiny interfaces like Reader (only 1 method) and Writer (only 1 method). Small interfaces are much easier to reuse! :::