英文:
How do I compare equality of function types?
问题
我正在进行一些测试,并尝试测试一些函数类型的相等性。我有以下代码:
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
}
我在文档中没有找到关于比较函数的内容,我知道我肯定漏掉了一些重要的东西,这就是为什么 reflect.DeepEqual
不能正确工作的原因。
英文:
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.
答案1
得分: 0
你可以像这样比较函数,了解有关函数表示的更多信息,请阅读此处: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()
}
例如: 这只是一个起点的想法。
func main() {
a := []someFunc{sf1, sf2}
b := []someFunc{sf1, sf2}
for idx, f := range a {
fmt.Println("Index: ", idx, funcEqual(f, b[idx]))
}
}
输出:
Index: 0 true
Index: 1 true
Play链接:https://play.golang.org/p/6cSVXSYfa5
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论