Closure
// Importing the "fmt" package, which provides functions for formatted I/O.
import "fmt"
// Function intSeq returns a closure: a function that "closes over" the variable i.
// The returned function can be used to generate a sequence of increasing integers.
func intSeq() func() int {
// Initialize a variable i.
i := 0
// Define and return an anonymous function (closure) that increments and returns i.
return func() int {
i++
return i
}
}
// The main function, which serves as the entry point for the program.
func main() {
// Call intSeq, which returns a function that will generate a sequence of integers.
nextInt := intSeq()
// Call the returned function, printing the next value in the sequence.
fmt.Println(nextInt())
// Call the returned function again, printing the next value in the sequence.
fmt.Println(nextInt())
// Call the returned function once more, printing the next value in the sequence.
fmt.Println(nextInt())
// Call intSeq again, creating a new closure with its own "i" variable.
newInts := intSeq()
// Call the new closure, printing the first value in its own sequence.
fmt.Println(newInts())
}Output
Last updated