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.

Radhakishan Surwase
Level Up Coding

--

Photo by Luca Bravo on Unsplash

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.

Code Listing 1.1 — Run on Go Playground

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.

Code Listing 1.2 — Run on Go Playground

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.

Code Listing 1.3 — Run on Go Playground

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.

Code Listing 1.4 — Run on Go Playground

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.

Code Listing 1.5 — Run on Go Playground

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.

Code Listing 1.6 — Run on Go Playground

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 😃

--

--

Innovative Golang Specialist | Golang Development | Scalable Architectures | Microservices | Docker | Kubernetes | Tech Writer | Programming Enthusiast