Traditionally, comparing two non-nil function pointers in Go involved the use of == or != operators. However, following recent changes, this approach now results in errors.
The elimination of pointer equality comparison for functions stems from the concept of equality vs. identity. In Go, == and != operators assess equivalence for values, not identity. This distinction aims to prevent confusion between these concepts.
Additionally, comparisons of functions impact performance. For instance, anonymous closures that do not refer to external variables should be optimized into a single implementation by the compiler. Comparing function pointers would hinder this optimization, requiring dynamic creation of new closures at runtime.
While it's possible to determine function identity using the reflect package, it's important to note that this approach entails undefined behavior. The results of such comparisons are unreliable, as the compiler may decide to collapse multiple functions into a single implementation.
To effectively compare function pointers, the following approach can be employed:
package main import "fmt" func F1() {} func F2() {} var F1_ID = F1 // Assign a unique variable to F1 var F2_ID = F2 // Assign a unique variable to 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 }
By employing pointers to unique variables associated with each function, you can effectively detect pointer equality among functions.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3