Home >Backend Development >Golang >How Can I Compare Function Pointers for Equality in Go?
In Go, comparing two non-nil function pointers for equality using the standard pointer equality operator == has become invalid in recent versions. This is a departure from the pre-Go1 behavior where function pointers could be compared for identity.
The prohibition on comparing function pointers for equality was motivated by the following reasons:
While direct pointer comparison of functions is no longer allowed, there are alternative approaches to achieve the desired behavior:
package main import "fmt" func F1() {} func F2() {} var F1_ID = F1 // Create a *unique* variable for F1 var F2_ID = F2 // Create a *unique* variable for F2 func main() { f1 := &F1_ID // Take the address of F1_ID f2 := &F2_ID // Take the address of F2_ID fmt.Println(f1 == f1) // Prints true fmt.Println(f1 == f2) // Prints false }
package main import "fmt" import "reflect" func SomeFun() {} func AnotherFun() {} func main() { sf1 := reflect.ValueOf(SomeFun) sf2 := reflect.ValueOf(SomeFun) fmt.Println(sf1.Pointer() == sf2.Pointer()) // Prints true af1 := reflect.ValueOf(AnotherFun) fmt.Println(sf1.Pointer() == af1.Pointer()) // Prints false }
Note: Using reflect relies on undefined behavior. It does not guarantee consistency across platforms or Go versions.
The above is the detailed content of How Can I Compare Function Pointers for Equality in Go?. For more information, please follow other related articles on the PHP Chinese website!