乐闻世界logo
搜索文章和话题

How to recurse a closure in Go?

1个答案

1

In Go, closures are anonymous functions that capture variables from their surrounding scope. To reuse closures, you can define a function that returns a closure. Each time you call this function, it creates a new closure instance. This way, even if the closures use the same internal logic, each closure's environment and state can be independent.

The following is a specific example demonstrating how to create and reuse closures in Go:

go
package main import "fmt" // Define a function that returns a closure func createCounter(start int) func() int { count := start // Returned closure return func() int { // Each time the closure is called, count increments count++ return count } } func main() { // Create two independent counter closures counter1 := createCounter(0) counter2 := createCounter(10) // Use the first counter fmt.Println(counter1()) // Output 1 fmt.Println(counter1()) // Output 2 // Use the second counter fmt.Println(counter2()) // Output 11 fmt.Println(counter2()) // Output 12 // Use the first counter again fmt.Println(counter1()) // Output 3 }

In this example, the createCounter function creates a new closure each time it is called. Each closure has its own independent count variable because each closure captures the environment state at the time it was created. Therefore, even though these closures use the same code logic, their states (i.e., the count variable) are independent and can be manipulated separately.

This approach makes closures ideal for use as generators or for constructing specific function instances, each with its own private state.

2024年7月26日 01:01 回复

你的答案