Go Closure Function Example

1. Introduction

In Go, a closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense, the function is "bound" to the variables. Closures are a powerful feature of Go that allows you to implement behavior that is dynamically controlled by the context in which it was created. Let's look at a simple example of a closure that encapsulates a counter.

Definition

A closure is a function that references variables from outside its immediate lexical scope. It has the ability to maintain state between function calls by capturing and storing references to its enclosing variables.

2. Program Steps

1. Define a function that creates a closure. This closure will act as a counter.

2. The closure will encapsulate a variable that maintains the count state.

3. Call the closure function multiple times to demonstrate how the state is maintained across function calls.

3. Code Program

package main

import "fmt"

// newCounter returns a closure function that maintains a count.
func newCounter() func() int {
	count := 0 // This variable is captured by the closure.
	return func() int {
		count++ // Increment the count each time the closure is called.
		return count
	}
}

func main() {
	counter := newCounter() // Create a new counter closure.

	// Call the counter function several times.
	fmt.Println(counter()) // Output: 1
	fmt.Println(counter()) // Output: 2
	fmt.Println(counter()) // Output: 3
}

Output:

1
2
3

Explanation:

1. package main - This defines the package name which contains the executable entry point.

2. import "fmt" - This imports the fmt package used for formatted I/O.

3. func newCounter() func() int - This function returns another function, which is a closure that maintains state between calls.

4. count := 0 - A variable count is defined and initialized to 0. This variable is captured by the closure returned by newCounter.

5. The returned function increments count and returns its updated value every time it is called.

6. In the main function, counter is a variable that holds the closure returned by newCounter.

7. When counter() is called, it maintains the state of count between calls, as shown by the increasing numbers printed each time counter() is invoked.

8. The output shows the count incrementing with each call to the counter closure, demonstrating how closures can encapsulate state.


Comments