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
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...
