Interfaces
Intermediate · Types & Methods
Interfaces are the heart of Go’s polymorphism. An interface lists method
signatures; any type with those methods satisfies it implicitly — no
implements keyword. Interface values hold a (concrete type, value) pair.
- interfaces1 — implicit satisfaction + polymorphism over
[]Shape - interfaces2 —
fmt.Stringerand the compile-timevar _ I = T{}check - interfaces3 — recovering the concrete type with a type switch / assertion
- interfaces4 — interface embedding (
ReadWriter=Reader+Writer)
Resources
Section titled “Resources”Exercises
Section titled “Exercises”interfaces1 test
Section titled “interfaces1 test”An interface is a set of method signatures. A type satisfies it IMPLICITLY,
Show hint
Add an Area method to each type — no implements keyword needed:
func (r Rectangle) Area() float64 { return r.W * r.H }func (c Circle) Area() float64 { return math.Pi * c.R * c.R }interfaces2 test
Section titled “interfaces2 test”Implementing fmt.Stringer (String() string) controls how a value prints.
Show hint
Implement String() string to satisfy fmt.Stringer:
func (p Point) String() string { return fmt.Sprintf("(%d, %d)", p.X, p.Y) }interfaces3 test
Section titled “interfaces3 test”Recover the concrete type held by an interface value with a type switch
Show hint
Type switch extracts the concrete type (import "fmt"):
switch x := v.(type) {case int: return fmt.Sprintf("int: %d", x)case string: return fmt.Sprintf("string: %s", x)default: return "unknown"}interfaces4 test
Section titled “interfaces4 test”Interfaces can embed other interfaces. A type satisfies the combined
Show hint
Implement both methods on *Buffer to satisfy the embedded interface:
func (b *Buffer) Read() string { return b.data }func (b *Buffer) Write(s string) { b.data += s }