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 types
Since 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).
More Related questions...