go by example part 2

This commit is contained in:
2022-01-01 19:47:24 +01:00
parent afe165089d
commit c1b7c64da2
10 changed files with 335 additions and 0 deletions

View File

@@ -0,0 +1,29 @@
package main
import "fmt"
// Go supports anonymous functions, which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it.
// intSeq returns another function, which is defined anonymously in the body of intSeq
// the returned function closes over the variable i to form a closure
func intSeq() func() int {
i := 0
return func() int {
i++
return i
}
}
func main() {
// call intSeq, assigning the result (a function) to nextInt
nextInt := intSeq()
// see the effect of the closure
fmt.Println(nextInt())
fmt.Println(nextInt())
fmt.Println(nextInt())
// confirm that the state is unique to that particular function
newInts := intSeq()
fmt.Println(newInts())
}