Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

对“1.12 流程控制:defer 延迟语句”这一章节中对“defer 后面跟的是匿名函数特殊场景进行解答”。 #25

Open
sankforever opened this issue Jun 24, 2021 · 1 comment

Comments

@sankforever
Copy link

sankforever commented Jun 24, 2021

因为在defer函数定义时,对外部变量的引用是有两种方式的,分别是作为函数参数和作为闭包引用。
使用匿名函数的话是没有将参数传递过去的,在最后调用是才去拿值。


import "fmt"

func main() {
	name := "go"
	defer func(name string) {
		fmt.Println(name) // 输出: go
	}(name)
	name = "python"
	fmt.Println(name) // 输出: python
}  // 这样输出就是python go
@iswbm
Copy link
Owner

iswbm commented Jan 21, 2022

关于这个问题,我加了两篇 defer 的文章,你可以看一下

  1. 7.14 说说 Go 中闭包的底层原理?
  2. 7.15 defer 的变量快照什么情况会失效?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants