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 slower
Rule: 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.
More Related questions...