Skip to content

Functions Cannot Compare

In go, there are some cases when we need to check functions in some cases:

  • check the equality of functions
  • compare two objects with function fields.

However, function type in Go is not addressable and not comparable.

it means that you cannot use ==, !=, & on a function like this:

func Test(){}
func main(){
    fmt.Println(Test==Test) //invalid
    fmt.Println(Test!=Test) //invalid
    fmt.Println(&Test) //invalid
}

When discussing “compare functions”, we compare the function variables instead of the function itself. Here comes a question: how can the variable that stores a function value call itself as calling the function? What’s the difference?

func d() {

}
func main() {
    f := d
    f()
}

The size of the function variable uses 8B, which is the same as OS I use. So, there is an implicit assigning operation inside the compile. The compiler gives the function address into the variable to help a program get data in memory.