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:
- def increment(amount):
- number += amount
- increment(1)
- 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
- def increment(amount):
- global number
- number += amount
- increment(1)
- increment(2)
Python
- def run():
- def increment(amount):
- return number + amount
- number = 0
- number = increment(1)
- number = increment(2)
- print number # 3
- run()
Go
- package main
- import "fmt"
- func main() {
- number := 0
- /* It has to be a local variable like this.
- You can't do `func increment(amount int) {` */
- increment := func(amount int) {
- number += amount
- }
- increment(1)
- increment(2)
- fmt.Println(number) // 3
- }