Golang / GoLang Interfaces and Object Oriented Interview Questions
How does equality work for interface values in Go?
Two interface values are equal (==) if and only if both their dynamic type and dynamic value are identical. If either interface is nil, both must be nil for equality. Comparing interfaces whose dynamic type is not comparable panics at runtime.
type Animal interface{ Sound() string }
type Dog struct{ Name string }
func (d Dog) Sound() string { return "Woof" }
var a1 Animal = Dog{Name: "Rex"}
var a2 Animal = Dog{Name: "Rex"}
var a3 Animal = Dog{Name: "Buddy"}
fmt.Println(a1 == a2) // true — same type, same value (Dog is comparable)
fmt.Println(a1 == a3) // false — same type, different Name
// Nil interface equality
var a4 Animal
fmt.Println(a4 == nil) // true — both words nil
fmt.Println(a1 == nil) // false — a1 holds a Dog
// Nil pointer in interface — NOT equal to nil
var d *Dog
var a5 Animal = d
fmt.Println(a5 == nil) // FALSE — type word is non-nil (*Dog)
// Comparing interfaces with non-comparable concrete types panics!
type BadAnimal interface{ Sound() string }
type SliceDog struct{ Tags []string }
func (s SliceDog) Sound() string { return "Woof" }
var b1 BadAnimal = SliceDog{Tags: []string{"cute"}}
var b2 BadAnimal = SliceDog{Tags: []string{"cute"}}
// fmt.Println(b1 == b2) // PANIC: runtime error: comparing uncomparable type SliceDog
// Safe comparison with reflect.DeepEqual
fmt.Println(reflect.DeepEqual(b1, b2)) // true — but slowerRule: interface comparison is safe only when you know the dynamic type is comparable (no slices, maps, or functions as fields). When in doubt, use reflect.DeepEqual for structural equality or compare fields directly after a type assertion.
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...
