dongtuoji5396 2017-07-16 23:23
浏览 44
已采纳

如何比较功能类型的相等性?

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条回答 默认 最新

  • duanlan8763 2017-07-16 23:35
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改