Introduction to VPS and Web Technology Development

golang的变量作用域

自由vps golang
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
}
示例2
package 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

使用chatGPT寻求答案
标签: 暂无标签

免责声明:

本站提供的资源,都来自网络,版权争议与本站无关,所有内容及软件的文章仅限用于学习和研究目的。不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负,我们不保证内容的长久可用性,通过使用本站内容随之而来的风险与本站无关,您必须在下载后的24个小时之内,从您的电脑/手机中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。侵删请致信E-mail:master@freevpsweb.com

同类推荐
评论列表