What is a closure in Golang?

Golang | Closure: Learn what is a closure function, explain the closure with examples in Golang.
Submitted by IncludeHelp, on October 05, 2021

Go programming language supports a special feature known as an anonymous function. An anonymous function can form a closure.

The closure is a special type of anonymous function that references variables declared outside of the function itself. This concept is similar to access the global variables which are available before the declaration of the function.

Consider the below example,

package main

import "fmt"

// Closure function
func counter() func() int {
	x := 0
	return func() int {
		x++
		return x
	}
}

func main() {
	cntfunc := counter()
	
	fmt.Println("[1] cntfunc():", cntfunc())
	fmt.Println("[2] cntfunc():", cntfunc())
	fmt.Println("[3] cntfunc():", cntfunc())
	fmt.Println("[4] cntfunc():", cntfunc())

	cntfunc = counter()
	fmt.Println("[5] cntfunc():", cntfunc())
}

Output:

[1] cntfunc(): 1
[2] cntfunc(): 2
[3] cntfunc(): 3
[4] cntfunc(): 4
[5] cntfunc(): 1

Golang FAQ »



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.