This article investigates how to leverage functional programming concepts in Go.
We will touch on the possibilities opened by the introduction of generics in Golang 1.18 and some limitations. Functional programming style helps us write code that is easy to understand, maintainable and testable.
Many underlying concepts have already found their way into the latest versions of widely used languages, notably the map/reduce pattern or the concept of optional values.
Guiding Principles
I would like to emphasize the following principles that are the basics of functional programming style:
Pure Golang Functions
As the name suggests, functional programming is all about writing functions. A function is considered pure if its output only depends on its input and if it does not have any side effects. Such kind of function offers several benefits:
- The function can be unit tested without having to set up complex mocks
- Pure functions can easily be used in multi-threaded environments. Since they do not have side effects, they also do not require synchronization of external data structures
- It’s typically easy to understand what the function is doing because you know that it does not have any side effects — by definition
Functions having side effects are considered impure. A side effect in this sense is any modification of a non-local state (i.e. changing global variables, mutating input arguments) or any form of I/O (reading/writing from streams or files, printing to the console, etc.).
There is no ads to display, Please add some