Closure Functions

Note in the Python example you can access number in the inner functionbut you can't change it. Suppose you wanted to do this:

  1. def increment(amount):
  2. number += amount
  3. increment(1)
  4. increment(2)

Then you would get a UnboundLocalError error because the variablewould be tied to the inner scope of the increment function.

Note: you can use the global statement, to get around that, example

  1. def increment(amount):
  2. global number
  3. number += amount
  4. increment(1)
  5. increment(2)

Python

  1. def run():
  2.  
  3. def increment(amount):
  4. return number + amount
  5.  
  6. number = 0
  7. number = increment(1)
  8. number = increment(2)
  9. print number # 3
  10.  
  11. run()

Go

  1. package main
  2.  
  3. import "fmt"
  4.  
  5. func main() {
  6.  
  7. number := 0
  8.  
  9. /* It has to be a local variable like this.
  10. You can't do `func increment(amount int) {` */
  11. increment := func(amount int) {
  12. number += amount
  13. }
  14. increment(1)
  15. increment(2)
  16.  
  17. fmt.Println(number) // 3
  18.  
  19. }