【问题标题】:Functions as members in structures作为结构中的成员的功能
【发布时间】:2019-02-02 15:20:07
【问题描述】:

我正在尝试在我的结构中发挥成员的作用

type myStruct struct {
    myFun func(interface{}) interface{}
}
func testFunc1(b bool) bool {
    //some functionality here
    //returns a boolean at the end
}
func testFunc2(s string) int {
    //some functionality like measuring the string length
    // returns an integer indicating the length
}
func main() {
    fr := myStruct{testFunc1}
    gr := myStruct{testFunc2}
}

我收到错误:

Cannot use testFunc (type func(b bool) bool) as type func(interface{}) interface{}
Inspection info: Reports composite literals with incompatible types and values.

我无法弄清楚为什么会出现此错误。

【问题讨论】:

    标签: function go struct field


    【解决方案1】:

    您的代码的问题是结构中的声明与testFunc 之间的类型不兼容。采用interface{} 并返回interface{} 的函数与采用并返回bool 的函数的类型不同,因此初始化失败。您粘贴的编译器错误消息就在这里。


    这将起作用:

    package main
    
    type myStruct struct {
        myFun func(bool) bool
    }
    
    func testFunc(b bool) bool {
        //some functionality here
        //returns a boolean at the end
        return true
    }
    
    func main() {
        fr := myStruct{testFunc}
    }
    

    【讨论】:

    • 我希望结构实例能够存储任何签名的函数,这就是我使用interface{} 作为参数和返回类型的原因。有不同的方法吗?我已经更新了问题以表明相同
    • @Murky:这行不通,因为 Go 目前没有泛型 [Go 2 的提案正在进行中:go.googlesource.com/proposal/+/master/design/…。现在完成它的唯一方法是让你的实际函数也使用interface{} 来处理所有事情,并使用类型开关进行运行时调度。或者,更改设计 - 您的真正问题很可能可以使用像接口这样的惯用 Go 结构来解决
    • @Murky,你的问题的答案is in the FAQ。也可以考虑阅读this
    • 感谢 @kostix 的 EliBendersky 清理一切。我将问题标记为已解决。
    • @Murky,我建议你考虑一下关于接口的想法,尤其是interface{} 多一点。 This excellent explanation 的接口有点过时但 99.9% 正确,它会向你解释 interface{} 不仅仅是一个(有点奇怪的)句法结构,意思是“任何类型”,但实际上是一个相当具体的类型:结构有两个指针大小的字段。这就是为什么bool(通常在内部是一个平台大小的int)不能以某种方式自动被该结构“匹配”;他们有不同的数据布局
    猜你喜欢
    • 2020-08-08
    • 2020-03-03
    • 2016-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多