Introduction
In Python you can assign default value to the functions, like so:
|
|
But in Go you can’t do this:
|
|
This will throw a syntax error. Try that?
In this post, we’ll see how can we overcome this issue the go way, with something called Function Options. Not sure if go is the only language that uses this syntax, if there is another language you are using, please let me know. Also, connect with me on LinkedIn
Also the end result will not look similar to the example above. But you will get the point and know how to proceed further.
Let us go step by step.
Functions are First-Class Citizens
In a language, functions are called the first-class citizen when they are treated like any other object and can be passed around like any other value. For example, a function can be passed as an argument to a function, can be returned by other functions and can be assigned as a value to a variable.
Python and JavaScript both are first-class function languages, so is Go.
This is more like an axiom on which we’ll build our proof on 😉. We’ll bulid more upon this in next section.
Variadic Function
We can’t have default parameters in our functions, but the language allows us to pass an unlimited number of parameters.
If you follow JavaScript, you must have seen the spread operator.
|
|
The same syntax is available in under the name variadic function. We can do similar thing in Go.
|
|
Functional Options
We can combine these both behavior of variadic function and first-class functions to pass an unlimined number of parameters to our main function.
For a simple example, let’s create a new function which creates a cup of coffee. The idea here is to define the constructor function which will make the base coffee, make it accept function as argument (because function are first-class citizen in Go) which are variadic (meaning it accept any number of argument).
|
|
The idea here is to keep signature of the all function which are going to be argument to be same as defined in the main function.
|
|
In the above over-simplified example, the signature is func(Coffee) Coffee
which means the all the functional option should take Coffee
as a param and also should return one for option to work.
You can also modify the functional argument to accept arguments in its own. The key is to keep the signature same.
|
|
The complete picture
Let’s finish our main package and test. I have added a Prepare
method on Coffee to demonstrate how composition works in Golang. Here is the complete code:
|
|
In a later post, I’ve demonstrated an alternative approach to functional options using Options struct. Both patterns are seen all over the Go ecosystem.
If you want to stay updated with articles like this, please subscribe to newsletter below.
Related readings: