Lab 05: Interfaces & Polymorphism
Overview
Step 1: Interface Definition & Implicit Implementation
package main
import (
"fmt"
"math"
)
type Shape interface {
Area() float64
Perimeter() float64
}
type Circle struct{ Radius float64 }
func (c Circle) Area() float64 { return math.Pi * c.Radius * c.Radius }
func (c Circle) Perimeter() float64 { return 2 * math.Pi * c.Radius }
type Rect struct{ W, H float64 }
func (r Rect) Area() float64 { return r.W * r.H }
func (r Rect) Perimeter() float64 { return 2 * (r.W + r.H) }
// Works with any Shape — polymorphism!
func printShape(s Shape) {
fmt.Printf("Area=%.2f Perimeter=%.2f\n", s.Area(), s.Perimeter())
}
func main() {
shapes := []Shape{
Circle{Radius: 5},
Rect{W: 4, H: 6},
}
for _, s := range shapes {
printShape(s)
}
}Step 2: Interface Composition
Step 3: Empty Interface — any
Step 4: Type Assertion
Step 5: Type Switch
Step 6: fmt.Stringer and io.Reader / io.Writer
Step 7: Interface Pitfalls — nil Interface vs nil Pointer
Step 8: Capstone — Plugin System via Interfaces
Summary
Concept
Key Points
Last updated
