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, fast
Decision 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.
More Related questions...