Tips on Maps & Errors
Explore how to implement set-like behavior using maps in Go to extract unique values, manage dependencies with simple tools, and adopt Go's explicit error handling approach. Understand best practices that help write clear and maintainable Go code without built-in set types or exceptions.
We'll cover the following...
Sets
You might want to find a way to extract unique value from a collection. In other languages, you often have a set data structure not allowing duplicates. Go doesn’t have that built in, however it’s not too hard to implement (due to a lack of generics, you do need to do that for most types, which can be cumbersome).
I used a few interesting tricks that are interesting to know. First, the map of empty structs:
We create a map with the keys being the values we want to be unique, the associated value doesn’t really matter much so it could be anything. For instance:
However I chose an empty structure because it will be as fast as a boolean but doesn’t allocate as much memory.
The second trick can been seen a bit further:
What we are doing here, is simply check if ...