Member-only story
7 Code Patterns in Go I Can’t Live Without
Code patterns to make your programs more reliable, efficient, and make your life easier
I’ve been developing EDR solutions for 7 years.
That means I have to write long-running system software that’s both resilient and efficient.
I heavily use Go for this job, and I’d like to share some of the most important code patterns that you can count on to make your program more reliable and efficient.
Use Maps as a Set
We often need to check the existence of something. For example, we might want to check if a file path/URL/ID has been visited before. In these cases, we can use map[string]struct{}
. For example:

Using an empty struct, struct{}
, means we don’t want the value part of the map to take up any space. Sometimes people use map[string]bool
, but benchmarks have shown that map[string]struct{}
perform better both in memory and time.
It’s also worth mentioning that map operations are generally considered to have O(1)
time complexity (StackOverflow), but go runtime provides no such guarantee.
Using chan struct{} to Synchronize Goroutines
Channels can carry data, but they don’t have to. Sometimes, we just need them for synchronization purposes.
In the following case, the channel carries a data type struct{}
, which is an empty struct that takes up no space. This is the same trick as in the previous map example:

Use Close to Broadcast
Continuing with the previous example, if we run multiple go hello(quit)
, then instead of sending multiple struct{}{}
to quit
, we can just close the quit
channel to broadcast the signal: