1
0
Fork 0
pr3-sose2026-fork/go/02-next-level/04-closure.go

29 lines
929 B
Go

package main
import "fmt"
// 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.
func intSeq() func() int { //returns a function that returns an int
i := 0 // i is a variable that intSeq's function value will reference. It continues to exist even after intSeq returns.
return func() int { // the anonomous function is returned here. It is not executed yet.
i++
return i
}
}
func main() {
//functions are first class citizens in Go, so we can assign them to variables,
// pass them as arguments to other functions, and return them from functions.
nextInt := intSeq()
fmt.Println(nextInt())
fmt.Println(nextInt())
fmt.Println(nextInt())
//a second function value from intSeq, with its own i variable.
newInts := intSeq()
fmt.Println(newInts())
}