Function Pointer Equality in Go
In Go, comparing function pointers for equality using == or != operators is not allowed for functions that are not nil. This behavior prevents the mixing of equality and identity comparisons.
Function equality differs from function identity. Identity comparisons should be used to determine if two functions are the same function, while equality comparisons should be used to determine if two functions are equivalent.
Using the reflect package to compare function identity, as shown in the Atom example, is considered undefined behavior. The compiler may optimize functions by merging their implementations, making the comparison unreliable.
To correctly compare function pointers for identity, you can create unique variables for each function and then compare the addresses of those variables. This approach ensures that you are comparing function pointers for the same function, regardless of optimizations.
Here is an example of how to compare function pointers for identity:
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 // Compare pointers fmt.Println(f1 == f1) // Prints true fmt.Println(f1 == f2) // Prints false }
The above is the detailed content of How Can I Safely Compare Function Pointers for Identity in Go?. For more information, please follow other related articles on the PHP Chinese website!