Source file tour/moretypes/function-closures.go

     1  //go:build OMIT
     2  
     3  package main
     4  
     5  import "fmt"
     6  
     7  func adder() func(int) int {
     8  	sum := 0
     9  	return func(x int) int {
    10  		sum += x
    11  		return sum
    12  	}
    13  }
    14  
    15  func main() {
    16  	pos, neg := adder(), adder()
    17  	for i := 0; i < 10; i++ {
    18  		fmt.Println(
    19  			pos(i),
    20  			neg(-2*i),
    21  		)
    22  	}
    23  }
    24  

View as plain text