What is the convention for organising interfaces and their implementations in a Go project?
I am new to Go and creating a small project, I currently have this folder structure:
src/
my-repo/
solve/
backtracksolve.go
permutatesolve.go
...
solver.go
... (some repositories and packages omitted for brevity) ...
backtracksolve
and permutatesolve
both implement the interface solver
so it make sense to keep them in the same package as the interface and other implementations of that interface, coming from Java/C# this is a common convention for example, java.util
contains interfaces such as Set
, Map
, List
, while also having implementations such as HashSet
, HashMap
and ArrayList
.
However in Go because they both implement a func Solve()
and both in the package solve
there is redeclared exception
.
Is it the convention to create a sub directory for each implementation (below) or something completely different?
src/
my-repo/
solve/
backtrack/
backtracksolve.go
permutation/
permutatesolve.go
solver.go
You would generally define different types that implement your Solver
interface and then define the Solve
function on those types.
func (s *BackTrackSolver) Solve() { … }
func (s *PermutateSolver) Solve() { … }
Because the types have distinct names there is no name clash. You can try it out online in the go playground.
About your package convention question: I think a good approach is to start with all code in a single package and only export the types and functions you actually want to expose to your callers. Then later when you your code cohesion drops you should start splitting out code into multiple packages.
Also have a look at the "Organizing Go code" article from the go blog, subsection "What to put into a package" (short read).