First-Class Functions in Golang
In Go, you can assign functions to variables, pass functions to functions, and even write functions that return functions. Functions are first-class — they work in all the places that integers, strings, and other types work.
Note: Before you go any further, I expect you all have a beginner-level understanding of Go syntax and primitive types to understand the source-code.
Assigning functions to variables
In the Go language, you are allowed to assign a function to a variable. When you assign a function to a variable, then the type of the variable is of function type and you can call that variable like a function call as shown in the below example.
Passing function to other functions
Variables can refer to functions, and variables can be passed to functions, which means Go allows you to pass functions to other functions.
Declaring function types
It’s possible to declare a new type for a function to condense and clarify the code that refers to it. Function types and function values can be used and passed around just like other values.
Closures and anonymous functions
An anonymous function also called a function literal in Go, is a function without a name. Unlike regular functions, function literals are closures because they keep references to variables in the surrounding scope.
Assign an anonymous function to a variable
You can assign an anonymous function to a variable and then use that variable like any other function.
Assign an anonymous function to a variable in the local scope
The variable you declare can be in the scope of the package or within a function, as shown in the next listing.
Returning function from the function
Anonymous functions can come in handy whenever you need to create a function on the fly. One such circumstance is when returning a function from another function. Although it’s possible for a function to return an existing named function, declaring and returning a new anonymous function is much more useful.
Conclusion
In this article, we have learned how we treat functions as simple variables. We can pass functions as parameters to another function. We can return a function from another function. We can assign functions to variables. We can define function types. When functions are treated as first-class, they open up new possibilities for splitting up and reusing code. To create functions on the fly, use anonymous functions with closures.
That's all for now…. Keep Learning… Happy Learning 😃