← blog
#2Coding guidelinesA2

Structs

Structs are not classes. I am sorry to break it to you.
If you treat them like classes, they will become unmanageable god objects - and you will fight the system (your codebase) the whole time.

A struct in Go is simply a state container that groups related things/data together: connection pool, cache, order item. If there is no state to hold or data to group, you probably just need a plain function that takes its data from input arguments.

Common mistakes I see developers bring from class-based (OOP) languages:

  • Setters and getters. If a field has no special logic, then export the field directly.
  • Passing the entire struct just to read a field or two. If a function only needs total and currency from an Order, then pass those two values only - not the entire struct.
  • The god object. One struct with a database, an HTTP client, a config and a logger. Just don't do that.

Keep it simple!