Golang / GoLang Interfaces and Object Oriented Interview Questions
How does Go achieve runtime polymorphism using interfaces?
Go achieves polymorphism through interface dispatch. When you call a method on an interface value, the runtime uses the itab's function pointer table to call the correct concrete implementation. This is equivalent to virtual method dispatch in C++ or Java.
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 Rectangle struct{ W, H float64 } func (r Rectangle) Area() float64 { return r.W * r.H } func (r Rectangle) Perimeter() float64 { return 2 * (r.W + r.H) } type Triangle struct{ A, B, C float64 } func (t Triangle) Area() float64 { s := (t.A + t.B + t.C) / 2 return math.Sqrt(s * (s-t.A) * (s-t.B) * (s-t.C)) } func (t Triangle) Perimeter() float64 { return t.A + t.B + t.C } // Polymorphic function â works on any Shape func printShapeInfo(s Shape) { fmt.Printf("%T â area=%.2f perimeter=%.2f\n", s, s.Area(), s.Perimeter()) } shapes := []Shape{ Circle{Radius: 5}, Rectangle{W: 4, H: 6}, Triangle{A: 3, B: 4, C: 5}, } for _, s := range shapes { printShapeInfo(s) // dynamic dispatch via itab each iteration } // main.Circle â area=78.54 perimeter=31.42 // main.Rectangle â area=24.00 perimeter=20.00 // main.Triangle â area=6.00 perimeter=12.00
Performance note: interface dispatch is one indirect function call through the itab (two pointer dereferences). For most code this is negligible. In tight loops profiling shows the bottleneck, concrete type calls or generics may be preferred. The Go compiler can devirtualise (inline) interface calls in some cases when it can prove the concrete type at compile time.
More Related questions...