go - 使用函数类型组

标签 go types

我想使用函数类型并将其中一些组合在一起(通常将它们传递给其他函数)。

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")
}

有没有办法在接口(interface)中使用它们?
否则,您知道使用结构而不是接口(interface)有什么缺点吗?

最佳答案

语法:

type blaer interface {
    bla
    bla2
}
声明一个带有两个成员变量的接口(interface),而不是方法。您不能在接口(interface)中声明变量。
当您在这样的结构中使用函数类型时:
type blaS struct {
    bla
    bla2
}
您正在做的是定义一个具有两个成员变量的结构,一个名为 bla类型 bla ,另一个名为 bla2类型 bla2 .您可以使用 s.bla()s.bla2()然而,这并不意味着 s实现假设接口(interface) blaer包含 blabla2方法。因为这两个函数指针不是 blaS 类型的方法, s不实现接口(interface)。
因此,确切的答案取决于您的用例。如果需要使用接口(interface),则必须将这两个函数定义为方法。如果您需要可以设置的函数指针,则必须使用结构。

关于go - 使用函数类型组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62959357/

相关文章:

go - http 查询字符串 : question mark becomes %3

mysql - 多个值存储在 MySQL 数据库的单个列中?

mongodb - 无法在golang项目中使用bongo连接到mongodb集群

go - 在DDD(纯净/六角形)架构中处理数据库连接和Env配置

go - 单值上下文中的多值选择.Text()

oracle - Rails 5 - created_at 和 updated_at 类

haskell - 表达无限种

go - struct golang 字段中的额外值

.net - 将 "obj"向下转换为底层数组类型(不带类型注释)

go - 为 switch 中的类型实现逻辑或