在围棋中,有没有办法比较两个非空函数指针来测试等价性?我的平等标准是指针相等.如果不允许,有什么特殊的原因不允许指针相等吗?
到目前为止,如果我试图以直截了当的方式做到这一点:
package main
import "fmt"
func SomeFun() {
}
func main() {
fmt.Println(SomeFun == SomeFun)
}
我得到了
./func-pointers.go:12: invalid operation: SomeFun == SomeFun (func can only be compared to nil)
据我了解,这一行为是最近引入的.
我已经使用Reflect包找到了答案;然而,Atom在下面建议,这实际上会产生未定义的行为.有关更多信息和可能的替代解决方案,请参阅Atom的帖子.
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())
af1 := reflect.ValueOf(AnotherFun)
fmt.Println(sf1.Pointer() == af1.Pointer())
}
输出:
true
false