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....
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
.