×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang program to demonstrate the function closure

Here, we are going to demonstrate the function closure in Golang (Go Language).
Submitted by Nidhi, on March 11, 2021 [Last updated : March 03, 2023]

Function Closure in Golang

Problem Solution:

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

Program/Source Code:

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

Golang code to implement the function closure

// 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.

Golang User-defined Function Programs »





Comments and Discussions!

Load comments ↻





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