Go 闭包函数里面,闭包内引用闭包外的函数局部变量的方式是引用方式(同一个内存地址)
package main import "fmt" func main() { f := closure(10) fmt.Println(f(1)) fmt.Println(f(2)) } func closure(a int) func(b int) int { fmt.Printf("first a %p \n", &a) fn := func(b int) int { a = 1 fmt.Printf("nei a %p \n", &a) return a + b } fmt.Printf("end a %p \n", &a) return fn }
运行结果:
first a 0xc042008158 end a 0xc042008158 nei a 0xc042008158 2 nei a 0xc042008158 3
可以从内存地址看到 a 的内存地址未变