Golang / GoLang Basics Interview Questions
What is the empty interface (any / interface{}) and when should you use it?
An interface with zero methods is satisfied by every type in Go. Written as interface{} or its alias any (Go 1.18+), it lets a variable or function parameter hold a value of any type. It is Go's mechanism for truly generic containers — at the cost of compile-time type safety.
// any is an alias for interface{} (Go 1.18+) func describe(v any) { fmt.Printf("Type: %-10T Value: %v\n", v, v) } describe(42) // Type: int Value: 42 describe("hello") // Type: string Value: hello describe([]int{1, 2, 3}) // Type: []int Value: [1 2 3] // Heterogeneous collection row := []any{1, "Alice", true, 3.14} // Must type-assert to get the concrete value back var v any = "hello" s, ok := v.(string) // safe â ok=false if not a string // s2 := v.(int) // panics if v is not an int // Type switch â handle multiple possible types for _, item := range row { switch x := item.(type) { case int: fmt.Println("int:", x) case string: fmt.Println("string:", x) case bool: fmt.Println("bool:", x) default: fmt.Println("other:", x) } } // PREFER: narrow interfaces, specific types, or generics over 'any' // 'any' loses compile-time type safety â errors become runtime panics
More Related questions...