Function 结构中的成员功能
我试图在我的组织中发挥成员的作用Function 结构中的成员功能,function,go,struct,field,Function,Go,Struct,Field,我试图在我的组织中发挥成员的作用 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
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.
我无法找出出现此错误的原因。您的代码的问题是结构中的声明和
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{}
作为参数和返回类型。有不同的方法吗?我已经更新了问题,以表明same@Murky:这将不起作用,因为Go目前没有泛型[有一个关于Go 2的建议正在进行:。现在完成它的唯一方法是让实际函数也使用接口{}
一切,并使用类型开关执行运行时调度。或者,更改设计-很可能您真正的问题可以使用惯用的Go结构解决,如interfaces@Murky回答你的问题。也考虑阅读。谢谢你清理了EliBendersky的东西,Kosix。我在回答这个问题。ky,我建议你考虑一下关于接口的想法,尤其是interface{}
。of interfaces有点过时,但99.9%是正确的,这将向你解释interface{}
不仅仅是一个(看起来有点奇怪的)语法结构,意思是“任何类型”但实际上是一种相当具体的类型:一个具有两个指针大小的字段的结构。这就是为什么bool
(内部通常是一个平台大小的int
)无法自动地被该结构“匹配”的原因;它们具有不同的不可靠数据布局