Golang - Code organisation with structs, variables and interfaces

A good model to check out is the source code of Go itself: http://golang.org/src

You will see that this approach (separating based on language items like struct, interface, ...) is never used.

All the files are based on features, and it is best to use a proximity principle approach, where you can find in the same file the definition of what you are using.
Generally, those features are grouped in one file per package, except for large ones, where one package is composed of many files (net, net/http)

If you want to separate anything, separate the source (xxx.go) from the tests/benchmarks (xxx_test.go)


As Thomas Jay Rush adds in the comments

Sometimes source code is automatically generated -- especially data structure definitions.
If the data structures are in the same file as the hand-wrought code, one must build capacity to preserve the hand-wrought portion in the code-generation phase.
If the data structures are separated in a different file, then inclusion allows one to simply write the data structure file without worry.


Dave Cheney offers an interesting perspective in "Absolute Unit (Test) @ LondonGophers" (March 2019)

You should take a broader view of the "unit" under test.
The units are not each internal function you write, but a whole package. Specifically the public API of a package.

Organizing your files to facilitate testing their Public API is a good idea.
accounts_struct_test.go would not, in that regards, make much sense.


See also "How I organize packages in Go" by Bartłomiej Klimczak

Sometimes, a few handlers or repositories are needed.
For example, some information can be stored in a database and then sent via an event to a different part of your platform. Keeping only one repository with a method like saveToDb() isn’t that handy at all.
All of elements like that are split by the functionality: repository_order.go or service_user.go.
If there are more than 3 types of the object, there are moved to a separate subfolder.


Here is my mental model for designing a package.

a. A package should encompass one idea or concept. http is a concept, http client or http message is not.

b. A file in a package should encompass a set of related types, a good rule of thumb is if two files share the same set of imports, merge them. Using the previous example, http/client.go, http/server.go are a good level of granularity

c. Don't do one file per type, that's not idiomatic Go.

Tags:

Go