golang,如何满足同一个包中多个文件的接口(interface)?

标签 go interface

我的应用有这样的逻辑:

myapp/
     |- tables/
              |-table1.go
              |-table2.go
              |-table3.go
      - main.go

在 main.go 中我有简单的界面:

type DBInterface interface {
    DataParse(string) string
}

现在,table1、table2、tableN 是数据库中的表名。我需要对特定表执行特定操作。因此,在 table1.go 中,我有一个简单的函数,它返回 table1.go 的已解析数据,其余部分返回一些数据。

现在,问题是我在 main.go 函数中有:

func ParseDataFromManyTables(dbs DBInterface) {
    // some actions on tables like: dbs.DataParse("tablename")
    // and these DataParse() are declared in tables/table*.go
}

我想做的是使用满足来自每个表/表*.go 文件(DataParse())的接口(interface)的函数。但问题是 - 这个函数不能在同一个包(这里是表)中重新声明,我可以在这里做得更好吗?我知道,我可能会创建新的包(目录),但我在这里似乎不是正确的方法....

最佳答案

你不能用一个函数来满足一个接口(interface)。只有具有方法的类型才能满足接口(interface)。

要满足接口(interface),您需要声明一个类型,然后在该类型上实现一组与接口(interface)方法集的方法签名相匹配的方法。

在这种情况下,您可以在每个文件中声明一个类型,并为每个类型实现一个与 DBInterfaceParseData 具有相同签名的方法:

table1.go

package tables

type Table1 struct{}

func (t Table1) DataParse(s string) string {
    // ...
    return "..."
}

table2.go

package tables

type Table2 struct{}

func (t Table2) DataParse(s string) string {
    // ...
    return "..."
}

鉴于此示例,您现在可以将 Table1Table2 类型的值传递给 ParseDataFromManyTables

关于golang,如何满足同一个包中多个文件的接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48422336/

相关文章:

dictionary - 戈朗 : Using a defined interface in a Map Value

google-app-engine - 在 Go Lang 中为整个结构设置标签

amazon-web-services - 如何向 AWS 验证 gocql

go - 使用 golang 将 DateTime 值插入 MS SQL

c# - 记录接口(interface)及其实现

c# - 不是按名称而是按类型指定接口(interface)成员

javascript - 接口(interface)中TypeScript函数声明的区别

git - 如何创建依赖于托管在 gitlab 子组中的私有(private) go 包的 docker 镜像?

delphi - 继承接口(interface)的接口(interface)委托(delegate)是否需要包装类?

java - 检查类是否实现接口(interface)