...

/

Tips on Maps & Errors

Tips on Maps & Errors

Useful tips and tricks for programming in Go.

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).

Press + to interact
// UniqStr returns a copy if the passed slice with only unique string results.
func UniqStr(col []string) []string {
m := map[string]struct{}{}
for _, v := range col {
if _, ok := m[v]; !ok {
m[v] = struct{}{}
}
}
list := make([]string, len(m))
i := 0
for v := range m {
list[i] = v
i++
}
return list
}

I used a few interesting tricks that are interesting to know. First, the map of empty structs:

Press + to interact
m := map[string]struct{}{}

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:

Press + to interact
m := map[string]bool{}

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 ...

Access this course and 1400+ top-rated courses and projects.