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.00Performance 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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
