我的应用有这样的逻辑:
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)方法集的方法签名相匹配的方法。
在这种情况下,您可以在每个文件中声明一个类型,并为每个类型实现一个与 DBInterface
的 ParseData
具有相同签名的方法:
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 "..."
}
鉴于此示例,您现在可以将 Table1
或 Table2
类型的值传递给 ParseDataFromManyTables
。
关于golang,如何满足同一个包中多个文件的接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48422336/