Google News
logo
Golang - Interview Questions
What are function closures?
Function closures is a function value that references variables from outside its body. The function may access and assign values to the referenced variables.
 
For example : adder() returns a closure, which is each bound to its own referenced sum variable.

package main

import "fmt"

func adder() func(int) int {
	sum := 0
	return func(x int) int {
		sum += x
		return sum
	}
}

func main() {
	pos, neg := adder(), adder()
	for i := 0; i < 10; i++ {
		fmt.Println(
			pos(i),
			neg(-2*i),
		)
	}
}​

Output :

0 0
1 -2
3 -6
6 -12
10 -20
15 -30
21 -42
28 -56
36 -72
45 -90

 

Advertisement