Methods & Interfaces
Go’s approach to polymorphism
Section titled “Go’s approach to polymorphism”Most object-oriented languages bolt polymorphism onto a class hierarchy: you declare that a type implements an interface, you extends a base class, and the compiler enforces the lineage. Go throws away the hierarchy entirely.
In Go, any named type can have methods, and any type that has the right methods automatically satisfies an interface — no declaration required. This is called implicit interface satisfaction, and it is the single most important design decision in the language.
The combination of methods and interfaces gives you:
- Polymorphism without inheritance trees.
- Dependency inversion without frameworks — accept an interface, return a struct.
- Composition without
extends— embed types to promote their fields and methods.
Module map
Section titled “Module map”| Lesson | What you will learn |
|---|---|
| Methods | Declare methods on any named type; value vs pointer receivers; method sets. |
| Interfaces | Define and satisfy interfaces implicitly; small interfaces; the empty interface any. |
| Type Assertions | x.(T), the comma-ok form, and switch v := x.(type). |
| Embedding | Struct embedding, promoted fields/methods, interface embedding, composition over inheritance. |
A first runnable example
Section titled “A first runnable example”The snippet below defines a method on a struct, declares a one-method interface, and calls the method through the interface — all in under 20 lines.
package main
import "fmt"
type Rectangle struct { Width, Height float64}
func (r Rectangle) Area() float64 { return r.Width * r.Height}
type Sizer interface { Area() float64}
func printArea(s Sizer) { fmt.Printf("area = %.2f\n", s.Area())}
func main() { r := Rectangle{Width: 4, Height: 3} fmt.Println(r.Area()) printArea(r)}Loading Go runtime (first run only, ~8 MB)…