Reason about interface comparison
Reason about interface comparison
Interface values can be compared using == and !=. Two interfaces are equal if both are nil, or if their dynamic types are identical and their dynamic values compare equal. If the identical dynamic type is not comparable, the comparison panics. Different dynamic types compare unequal without comparing their contents.
package main
import ( "fmt")
type Score int
func main() { var a any = 7 var b any = Score(7) var c any = 7 fmt.Println(a == b, a == c) var d any = []int{1} fmt.Println(d == nil, d == a)}An int and a Score have different dynamic types. Two int values can be compared normally. The slice-containing interface can be compared with nil and with an interface containing a different dynamic type; comparing it to another interface with the same slice type would panic.
Expected output:
false truefalse falseCompare only a supported concrete type
package main
import ( "fmt")
func equalInt(a, b any) (bool, bool) { x, ok := a.(int) if !ok { return false, false } y, ok := b.(int) if !ok { return false, false } return x == y, true}func main() { fmt.Println(equalInt(2, 2)) fmt.Println(equalInt(2, 3)) fmt.Println(equalInt([]int{2}, []int{2}))}The second boolean says whether the comparison was supported. This intentionally handles only int rather than pretending to compare every possible interface value. A map with interface keys can likewise panic on insertion of a noncomparable dynamic key. Prefer a concrete comparable key type when possible.
Expected output:
true truefalse truefalse falseTry it locally
Assign "Go" to two any variables and []int{1} to a third. Print whether the first two are equal and whether the third equals nil. Do not compare two slice-containing interfaces.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Interfaces 08: Reason about interface comparison
Check the lesson objective before moving on.
What happens when two any values both contain []int and are compared?
Is comparing a non-nil interface holding a slice with nil safe?