Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

闭包

func TestCloser(t *testing.T) {
	x := func() func() {
		var i = 1
		return func() {
			i++
			log.Println("i = ", i)
		}
	}()
	x()
	x()
}

输出结果:

=== RUN   TestCloser
2022/04/10 21:42:09 2
2022/04/10 21:42:09 3
--- PASS: TestCloser (0.01s)

闭包持有外部变量i