Knaph

Interfaces

Interfaces

An interface defines a set of methods a type must have — without that type ever declaring which interfaces it implements. This is the biggest structural difference from class-based inheritance you're likely used to:

type Shape interface {
	Area() float64
}

Any type with an Area() float64 method automatically satisfies Shape — no Rectangle implements Shape anywhere:

type Circle struct {
	Radius float64
}
 
func (c Circle) Area() float64 {
	return 3.14159 * c.Radius * c.Radius
}
 
func printArea(s Shape) {
	fmt.Println(s.Area())
}
 
printArea(Rectangle{Width: 3, Height: 4}) // 12
printArea(Circle{Radius: 2})              // 12.56636

printArea doesn't know or care whether it received a Rectangle or a Circle — only that whatever it got has an Area() float64 method. This is called structural typing: satisfying an interface is about having the right shape, not about declaring a relationship. It's the same idea as Python's duck typing ("if it walks like a duck and quacks like a duck..."), except Go checks it at compile time instead of discovering a missing method at runtime.

Why this matters in practice

Structural typing means you can define a small interface for exactly what your function needs, and any existing type — including ones from a library you don't control and can't modify — satisfies it automatically as long as it has the right methods. You never need to go back and retrofit an implements declaration onto a type just so it can be used somewhere new.

The empty interface and any

interface{} (aliased as any in modern Go) has zero required methods, so every type satisfies it:

func describe(v any) {
	fmt.Printf("value: %v, type: %T\n", v, v)
}
 
describe(42)        // value: 42, type: int
describe("hello")   // value: hello, type: string

This is Go's escape hatch for "I genuinely don't know the type ahead of time" — used sparingly, since it gives up the compile-time type checking that's most of the point of using Go in the first place.

Sign in to track your progress through this course.

Ask an AI

Open a ready-made prompt in ChatGPT or Claude — just press Enter.

SummarizeChatGPTClaude
Ask me questionsChatGPTClaude
Let's learn togetherChatGPTClaude