ADVERTISEMENT
ADVERTISEMENT

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 »

ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.