我想使用函数类型并将它们中的一些组合在一起(通常将它们传递给其他函数)。
type bla func()
type bla2 func(string)
/* this one doesn't compile...
type blaer interface {
bla
bla2
}
*/
// this one compiles
type blaS struct {
bla
bla2
}
func main() {
s := blaS{
bla : func(){fmt.Println("Hello, playground")},
bla2 : func(s string){fmt.Println("Hello, ", s)},
}
s.bla()
s.bla2("world")
}
有没有办法在接口中使用它们?否则,您知道使用结构而不是接口有什么缺点吗?
最佳答案
语法:
type blaer interface {
bla
bla2
}
在声明一个带有两个成员变量而不是方法的接口。您不能在接口中声明变量。当在这样的结构中使用函数类型时:
type blaS struct {
bla
bla2
}
您正在执行的操作是使用两个成员变量定义一个结构,一个名为bla
类型的名为bla
,另一个名为bla2
类型的bla2
。您可以使用s.bla()
和s.bla2()
,但这并不意味着s
实现了包含blaer
和bla
方法的假设接口bla2
。因为这两个函数指针不是blaS
类型的方法,所以s
无法实现该接口。因此,确切的答案取决于您的用例。如果需要使用接口,则必须将这两个函数定义为方法。如果需要可以设置的函数指针,则必须使用结构。