Where are “contains”, “map”, “reduce”, etc. functions in Golang (Go)?

Wacław The Developer
2 min readApr 10, 2022

Introduction

Many people who started their programming career from Python, C# and other languages. There are typical functions for data manipulations. For example — simple contains() function to check if the array contains an element. Programmers, who became to work with Go, were faced with a lack of helpful standard functions. Today I want to describe the situation, why such functions don’t exist in Go, and what i propose to do with that.

Why Go (Golang) don’t have such functions

Lack of generics (go version ≤1.18)

Imagine the situation, where you need to implement contains() function. I think you will use the loop and == operator. If you will try to create universal contains() function — you will need the generics with the comparable data type (that supports == operation).

Generics are always slower (go version ≥1.18)

Many people had a dream about generics in Go. Generics were added in go version 1.18 (15 March 2022), but using generics, you are making your code slower. Just google the benchmark results.

Philosophy of Go

So, Go was created as a simple and very fast language. The authors prefer to avoid the practice of forcing you to use slower solutions. According to this — the best way is to write the required function once, that accepts your data type. This will provide the best performance. For example:

func contains(s []string, e string) bool {
for _, elem := range s {
if elem == e {
return true
}
}
return false
}

If you (still) would like to use universal functions for data manipulation:

If your project has soft requirements in part of the performance and you are ready to use go version ≥1.18 — you can take a look at my package (https://github.com/waclawthedev/go-sugaring)

It is very easy to use.

  1. go get github.com/waclawthedev/go-sugaring
  2. call sugar.Contains() with an array of any comparable type. For now, (10.04.2022, v.1.0) package contains the next functions:

1. sugar.Contains - check if slice contains element
2. sugar.IndexesOf - get the slice with occurrences (indexes) of element in slice
3. sugar.Map - Map function. Python analog
4. sugar.Filter - Filter function. Python analog
5. sugar.Reduce - Reduce function. Python analog
6. sugar.Flatten - Transforms matrix to slice
7. sugar.Min - min element in slice
8. sugar.Max - max element in slice
9. sugar.Keys - get keys of map as slice
10. sugar.Values - get values of map as slice

Instead of conclusion:

I advise you to choose the right solution for your project. If you prefer comfortable programming to maximum performance — you can use my or another package with generics-based functions or get inspiration to write your own flexible solution.

P.S. If you have questions about go-sugaring — feel free to create the issue on GitHub :)

--

--