package main import "fmt" func main() { x := 42 fmt.Println(x) foo() } func foo() { // no access to x // this does not compile fmt.Println(x) }
闭包作用域
package main import "fmt" func main() { x := 42 fmt.Println(x) { fmt.Println(x) y := "The credit belongs with the one who is in the ring." fmt.Println(y) } fmt.Println(y) // outside scope of y }示例2package main import "fmt" func main() { x := 0 increment := func() int { x++ return x } fmt.Println(increment()) fmt.Println(increment()) } /* closure helps us limit the scope of variables used by multiple functions without closure, for two or more funcs to have access to the same variable, that variable would need to be package scope anonymous function a function without a name func expression assigning a func to a variable */GOROOT=C:\Program Files\Go #gosetup
GOPATH=C:\Users\EDZ\go #gosetup
"C:\Program Files\Go\bin\go.exe" build -o C:\Users\EDZ\AppData\Local\Temp\GoLand\___2go_build_main_go__2_.exe C:\Users\EDZ\Desktop\GolangTraining\04_scope\02_block-scope\02_closure\03\main.go #gosetup
C:\Users\EDZ\AppData\Local\Temp\GoLand\___2go_build_main_go__2_.exe #gosetup
1
2
进程 已完成,退出代码为 0
变量覆盖package main import "fmt" func max(x int) int { return 42 + x } func main() { max := max(7) fmt.Println(max) // max is now the result, not the function } // don't do this; bad coding practice to shadow variables