Golang / GoLang Interfaces and Object Oriented Interview Questions
What is the empty interface (any) in Go and what are its trade-offs?
The empty interface interface{} — aliased as any since Go 1.18 — has no methods. Because every type implements zero or more methods, every type satisfies the empty interface. It is Go's equivalent of Java's Object or C's void*.
// any is an alias for interface{} (Go 1.18+)
func printAnything(v any) {
fmt.Printf("%T: %v\n", v, v)
}
printAnything(42) // int: 42
printAnything("hello") // string: hello
printAnything([]int{1,2}) // []int: [1 2]
// Common use: heterogeneous collections
data := map[string]any{
"name": "Alice",
"age": 30,
"tags": []string{"admin"},
}
// Recover the concrete type with type assertion
name, ok := data["name"].(string) // ok=true, name="Alice"
age, ok := data["age"].(int) // ok=true, age=30
_, ok = data["name"].(int) // ok=false — not an int
// Type switch — idiomatic multi-type handling
func describe(v any) string {
switch t := v.(type) {
case int: return fmt.Sprintf("int=%d", t)
case string: return fmt.Sprintf("str=%q", t)
case bool: return fmt.Sprintf("bool=%v", t)
default: return fmt.Sprintf("unknown(%T)", t)
}
}
// Trade-offs of any:
// PROS: flexible, universal container, JSON unmarshalling
// CONS: no compile-time type safety, requires runtime assertions,
// values often escape to heap, slower than concrete types
// PREFER generics (Go 1.18+) when the algorithm is uniform across typesSince Go 1.18, the preferred approach for type-agnostic functions is generics rather than any: generics preserve compile-time type safety and allow the compiler to generate more efficient code. Use any when you genuinely need to store or pass values of unpredictable types (JSON, configuration, middleware context).
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...
