Go from Beginner to Expert: A Complete Guide to Learn Golang PART-9

Go from Beginner to Expert: A Complete Guide to Learn Golang PART-9

Step-by-Step Guide to understand Functions (Scope, Anonymous, Closures) of Golang

Md. Faiyaj Zaman
2 min readJan 12, 2023

--

Welcome back! In the previous tutorial, we covered the basics of functions, basics of creating and using functions in Golang, but there’s one more important concept we need to discuss before moving on: function scope, anonymous function and closures.

1Function Scope

Function scope refers to the visibility and accessibility of variables within a function. Variables defined inside a function are only accessible within that function, which is called local scope. Global scope variables, on the other hand, are accessible from anywhere in the program. In Go, global variables are defined outside of any function, whereas local variables are defined inside a function block.

var globalVariable int // global variable

func myFunc(){

localVariable := 2 // local variable

// do something with localVariable

}

2Anonymous functions

Another concept related to functions are anonymous functions. Anonymous functions are functions that are defined without a name, and are often used as function literals, that is to say, functions that are defined and passed as an argument to another function.

For example:

func main() {

func() {

fmt.Println("Hello, World!")

}() // this anonymous function is immediately invoked

}

3Closures

Closures, on the other hand, are a special type of anonymous function that can “remember” the values of the variables in the scope where they were defined, even after the function that defined them has returned.

Closures are often used to create small, reusable bits of functionality that can be passed around as arguments to other functions.

Here is an example of closure where we define a function that accepts a string and returns another function, that takes no argument and returns that string:

func sayHello() func() string {

greeting := "Hello"

return func() string {

return greeting

}

}

Closures are a powerful feature of Golang, and they can be used in a variety of ways, such as in creating callbacks, event handlers, and more.

That’s it for function scope, anonymous function and closures in Golang. Next we will look into some advanced topics like Variadic functions, defer and recursion that can help you to write robust and maintainable code.

Thanks for reading!

Happy Coding :)

--

--