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 compared
Memory 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.
More Related questions...