Golang / GoLang Interfaces and Object Oriented Interview Questions
What are the edge cases in Go interface value equality that trip up experienced developers?
Interface equality has several subtle edge cases that are distinct from what most developers expect:
// Case 1: nil interface vs interface holding nil pointer
var p *int
var i interface{} = p // i has type *int, data nil
fmt.Println(p == nil) // true — p is a nil pointer
fmt.Println(i == nil) // FALSE — i has a non-nil type word
// Case 2: two different interface types wrapping the same concrete value
type A interface{ Foo() }
type B interface{ Foo() }
type S struct{}
func (S) Foo() {}
var a A = S{}
var b B = S{}
// a == b // COMPILE ERROR: invalid operation — a and b are different interface types
// But:
fmt.Println(reflect.DeepEqual(a, b)) // true — same concrete type and value
// Case 3: two interface values of the same type
var a1 A = S{}
var a2 A = S{}
fmt.Println(a1 == a2) // true — S{} == S{} (empty struct is comparable)
// Case 4: interface wrapping uncomparable type — RUNTIME PANIC
type WithSlice struct{ s []int }
func (WithSlice) Foo() {}
var a3 A = WithSlice{s: []int{1}}
var a4 A = WithSlice{s: []int{1}}
// fmt.Println(a3 == a4) // PANIC: runtime error: comparing uncomparable type main.WithSlice
// Case 5: comparing interface to its concrete value directly
var s interface{} = "hello"
fmt.Println(s == "hello") // true — right side promoted to interface, then comparedMemory aid: interface equality checks (1) that both type words are identical AND (2) that both data values are equal using the concrete type's == operator. If the concrete type is not comparable (contains slices, maps, functions), the comparison panics. Use reflect.DeepEqual for structural comparison when the type might be non-comparable.
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...
