How to compare two interfaces in Go?

Technology CommunityCategory: GolangHow to compare two interfaces in Go?
VietMX Staff asked 3 years ago

You can compare two interfaces with the == operator as long as the underlying types are “simple” and identical. Otherwise the code will panic at runtime:

var a interface{}
var b interface{}

a = 10
b = 10
println(a == b)
// Output: true

a = []int{1}
b = []int{2}
println(a == b)
// Output: panic: runtime error: comparing uncomparable type []int

Both structs and interfaces which contain maps, slices (but not functions) can be compared with the reflect.DeepEqual() function:

var a interface{}
var b interface{}

a = []int{1}
b = []int{1}
println(reflect.DeepEqual(a, b))
// Output: true

a = map[string]string{"A": "B"}
b = map[string]string{"A": "B"}
println(reflect.DeepEqual(a, b))
// Output: true

temp := func() {}
a = temp
b = temp
println(reflect.DeepEqual(a, b))
// Output: false