← blog
#3Coding guidelinesA3

Interfaces

Accept interfaces, return structs. This is by far the hardest one for new Go developers.

They keep refusing it, without even trying it first. Then they complain about the code being hard to maintain.

When you return an interface you loose the context. It hides every method that isn't on it, so the first caller who needs something new, adds it to the interface. Then the next caller adds one more. Eventually it becomes a bloated copy of the struct, and every mock in your tests has to implement all of it too.

Define on demand, where it's used, literally next to the code that calls it.

Add interface when you have two or more real implementations, or when you need to decouple from something you don't control (a payment API, a message broker, a cloud SDK) so it can be mocked in tests.

Give the above two rules a try and see how it goes. You will be surprised how much better it is.

Red flag: an interface and a struct that implements it in the same file - that's actually the same type written twice.