dscojuxf69080 2018-01-24 12:18
浏览 197

golang,如何满足同一包中许多文件的接口?

I have this logic of my app:

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

In main.go I have simple interface:

type DBInterface interface {
    DataParse(string) string
}

Now, table1, table2, tableN are name of tables in DB. I need to perform specific action on specific table. Hence, in table1.go I have simple function which returns parsed data for table1.go, some for the rest.

Now, problem is that I have in main.go function:

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

What I wanted to do is to use function which satisfies interface from each tables/table*.go file (DataParse()). But the problem is - this function cannot be redeclared in same package (tables here), what I can do better here? I know, that I may create new packages(directories) but I does not seem to be correct approach here....

  • 写回答

1条回答 默认 最新

  • dongxun2903 2018-01-24 12:51
    关注

    You cannot satisfy an interface with a function. Only types with methods can satisfy an interface.

    To satisfy an interface you need to declare a type and then implement a set of methods on that type that match the method signatures of the interface's method set.

    In you case you can declare a type in each of your files and for each of those types implement a method that has the same signature as DBInterface's 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 "..."
    }
    

    Given this example you can now pass a value of type Table1 or Table2 to ParseDataFromManyTables.

    评论

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图