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

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

报告相同问题?

悬赏问题

  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验