Welcome To Golang By Example

Interface Comparison in Go (Golang)

For understanding whether two interface variables are equal or not, we first need to understand the internal representation of an interface. Like any other variable, an interface variable is represented by a type and value. Interface variable value, in turn under the hood, consists of two tuple

See below diagram which illustrates what we mentioned above

Two interface are comparable if either

Some of the comparable types as defined by go specification are

Some of the types which are not comparable as per go specification

Two interface variable can be compared using == or != operators

Let’s see a program

package main

import "fmt"

type animal interface {
	breathe()
	walk()
}

type lion struct {
	age int
}

func (l lion) breathe() {
	fmt.Println("Lion breathes")
}

func (l lion) walk() {
	fmt.Println("Lion walk")
}

func main() {
	var a animal
	var b animal
	var c animal
	var d animal
	var e animal

	a = lion{age: 10}
	b = lion{age: 10}
	c = lion{age: 5}

	if a == b {
		fmt.Println("a and b are equal")
	} else {
		fmt.Println("a and b are not equal")
	}

	if a == c {
		fmt.Println("a and c are equal")
	} else {
		fmt.Println("a and c are not equal")
	}

	if d == e {
		fmt.Println("d and e are equal")
	} else {
		fmt.Println("d and e are not equal")
	}
}

Output

a and b are equal
a and c are not equal
d and e are equal

In the above program, we have animal interface and we have a lion struct that implements the animal interface by defining two of its methods.

Interface variable a and b are equal because

First two points also apply for comparing a and c, but they are not equal because

Interface variable d and e are equal because