Golang / GoLang Interfaces and Object Oriented Interview Questions
When should you use reflection instead of interfaces for type-agnostic code in Go?
Both interfaces and reflection allow code to work with values of unknown types at runtime, but they differ fundamentally in safety, performance, and intent.
| Aspect | Interface | Reflection (reflect package) |
|---|---|---|
| Type safety | Compile-time method set checked | Fully runtime — panics on misuse |
| Performance | One indirect call (itab) | 10–100x slower |
| Expressiveness | Only call declared methods | Inspect any field, call any method, set values |
| Use when | You know the contract (method set) at design time | Contract unknown at compile time (marshalling, ORM, DI frameworks) |
| Discoverability | Interface name is self-documenting | Code is harder to follow and trace |
// Interface approach — compile-time safety
type Serialiser interface{ Serialise() []byte }
func saveToFile(s Serialiser, path string) error {
return os.WriteFile(path, s.Serialise(), 0644)
}
// Reflection approach — needed when structure is unknown at compile time
// (like JSON encoding)
func toMap(v any) map[string]any {
result := make(map[string]any)
val := reflect.ValueOf(v)
if val.Kind() == reflect.Ptr { val = val.Elem() }
if val.Kind() != reflect.Struct { return nil }
typ := val.Type()
for i := 0; i < val.NumField(); i++ {
field := typ.Field(i)
if !field.IsExported() { continue }
key := field.Tag.Get("json")
if key == "" { key = field.Name }
result[key] = val.Field(i).Interface()
}
return result
}
// Generics (Go 1.18+) — preferred over reflection for type-agnostic algorithms
func Map[T, U any](slice []T, f func(T) U) []U {
result := make([]U, len(slice))
for i, v := range slice { result[i] = f(v) }
return result
}
// No reflection, compile-time safe, fastDecision guide: (1) use an interface when the contract is known at design time; (2) use generics when the algorithm is identical across types; (3) use reflection only when you must work with arbitrary struct layouts or types unknown until runtime — JSON encoding, ORM field mapping, dependency injection containers.
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...
