Golang Anonymous Function Closure with Example

golang anonymous function closure

In the previous blog, we learned about Function Syntax in Golang and Variadic Arguments. This time we will learn about Anonymous Function in Golang, Return values, and scope of the variable inside an anonymous function in Golang (Closure).

Read Function in Golang to understand Golang Anonymous Function and Closure better.

Golang Anonymous Function

Function without a name is called anonymous function.

Example:

func main() {

	func() {
		fmt.Println("Welcome to Golang Functions!")
	}()

}

Welcome to Golang Functions!

In Golang, Anonymous functions are invoked immediately so they are also called Immediately invoked function expression (IIFE).

Golang Anonymous Function Parameters

func main() {

	msg := "Hello Go World!"

	func(msg string) {
		fmt.Println(msg)
	}(msg)

}

Hello Go World!

In the example above, the anonymous function can use the main function’s msg variable but this is not a good practice in long run.

The Anonymous functions in Golang must have its own parameters if they want to use the global variable.

Golang Anonymous functions Assignment

func main() {

	var f func() = func() {
		fmt.Println("Hello Golang Functions")
	}

	f()

}

Hello Golang Functions

An Anonymous function in Golang can also be assigned to a variable of func() type, and later can be invoked using that variable.

Short declaration:

f := func() { // Body }

Parameters in Golang anonymous function assigned variable:

func main() {

	msg := "Hello World"

	var f func(string) = func(msg string) {
		fmt.Println(msg)
	}

	f(msg)

}

Hello World

When passing parameters to Golang Anonymous function assigned variable, the func() type also has to be notified of the parameters.

Golang Closure

In the above example, the msg variable is passed to the anonymous function through a parameter, but an anonymous function can access the outer variable because of the property of closure in Golang.

Closure Example:

func main() {

	msg := "Hello World"

	func() {
		fmt.Println(msg)
	}()

}

Golang Anonymous function Return Values

func main() {

	var divide func(int, int) (int, int)

	divide = func(a, b int) (int, int) {
		if a%b == 0 {
			return a / b, 0
		}
		return a / b, a % b
	}
	quotient, remainder := divide(5, 3)
	fmt.Println("Quotient of 5/3 = ", quotient)
	fmt.Println("Remainder of 5/3 = ", remainder)

}

Quotient of 5/3 = 1
Remainder of 5/3 = 2

Learn more about Golang Functions, Anonymous Functions, and Methods from the official Golang Documentation.

Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *