Q:

Golang program to demonstrate the function closure

belongs to collection: Golang User-defined Function Programs

0

In this program, we will demonstrate the function closure. Closure functions are functions, that return another function.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to demonstrate the function closure is given below. The given program is compiled and executed successfully.

// Golang program to demonstrate the function closure

package main

import "fmt"

func resetVal() func() int {
	i := 10
	return func() int {
		i -= 1
		return i
	}
}

func main() {
	decrraseVal1 := resetVal()
	fmt.Println(decrraseVal1())
	fmt.Println(decrraseVal1())

	decrraseVal2 := resetVal()
	fmt.Println(decrraseVal2())
	fmt.Println(decrraseVal2())
	fmt.Println(decrraseVal2())
}

Output:

9
8
9
8
7

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.

func resetVal() func() int {
   i:=10
   return func() int {
      i-=1
      return i  
   }
}

In the above code, we created a resetVal() closure function that returns another function.

In the main() function, we called resetVal() function to get initial value of local variable i that is 10. Here, we used decrraseVal1 and decrraseVal2 to implement function closure and call nested function.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Golang program to implement a user-defined functio... >>
<< Golang program to return multiple values from a us...