Skip to content

Methods & Interfaces

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.
LessonWhat you will learn
MethodsDeclare methods on any named type; value vs pointer receivers; method sets.
InterfacesDefine and satisfy interfaces implicitly; small interfaces; the empty interface any.
Type Assertionsx.(T), the comma-ok form, and switch v := x.(type).
EmbeddingStruct embedding, promoted fields/methods, interface embedding, composition over inheritance.

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)
}
How does a Go type declare that it satisfies an interface?
Which of the following can have methods in Go?
What is the idiomatic Go substitute for class inheritance?