如何比较功能类型的相等性?
问题描述:
I am doing some testing and trying to test for equality of some function types. I have https://play.golang.org/p/GeE_YJF5lz :
package main
import (
"fmt"
"reflect"
)
type myStruct struct {
f []someFunc
}
type someFunc func(a string) bool
var sf1 someFunc = func(a string) bool {
return true
}
var sf2 someFunc = func(a string) bool {
return false
}
func main() {
a := []someFunc{sf1, sf2}
b := []someFunc{sf1, sf2}
fmt.Println(reflect.DeepEqual(a, b)) // false
m := &myStruct{
f: []someFunc{sf1, sf2},
}
n := &myStruct{
f: []someFunc{sf1, sf2},
}
fmt.Println(reflect.DeepEqual(m, n)) // false
}
I haven't been able to find anything in the docs about comparing functions and know I must be missing something important as to why reflect.DeepEqual doesn't work for them properly.
答
You can compare function like this, Read more about the representation of functions here: http://golang.org/s/go11func
func funcEqual(a, b interface{}) bool {
av := reflect.ValueOf(&a).Elem()
bv := reflect.ValueOf(&b).Elem()
return av.InterfaceData() == bv.InterfaceData()
}
For example: This is just an idea for your start point.
func main() {
a := []someFunc{sf1, sf2}
b := []someFunc{sf1, sf2}
for idx, f := range a {
fmt.Println("Index: ", idx, funcEqual(f, b[idx]))
}
}
Output:
Index: 0 true
Index: 1 true
Play link: https://play.golang.org/p/6cSVXSYfa5