go语言---闭包

什么是闭包?

闭包就是能够读取其他函数内部变量的函数。例如在javascript中,只有函数内部的子函数才能读取局部变量,所以闭包可以理解成“定义在一个函数内部的函数“。在本质上,闭包是将函数内部和函数外部连接起来的桥梁。

闭包包含自由(未绑定到特定对象)变量,这些变量不是在这个代码块内或者任何全局上下文中定义的,而是在定义代码块的环境中定义(局部变量)。“闭包” 一词来源于以下两者的结合:要执行的代码块(由于自由变量被包含在代码块中,这些自由变量以及它们引用的对象没有被释放)和为自由变量提供绑定的计算环境(作用域)。在PHP、Scala、Scheme、Common Lisp、Smalltalk、Groovy、JavaScript、Ruby、 Python、Go、Lua、objective c、swift 以及Java(Java8及以上)等语言中都能找到对闭包不同程度的支持。

go语言代码示例:

package main

import "fmt"

func main() {
	// 调用
	f1 := Closure()
	fmt.Println(f1())  // 0xc0000a0090 : 2
	fmt.Println(f1())  // 0xc0000a0090 : 3
	fmt.Println(f1())  // 0xc0000a0090 : 4
	fmt.Println(f1())  // 0xc0000a0090 : 5

	f2 := Closure()
	fmt.Println(f2())  // 0xc0000a00d8 : 2
	fmt.Println(f2())  // 0xc0000a00d8 : 3
	fmt.Println(f2())  // 0xc0000a00d8 : 4
	fmt.Println(f2())  // 0xc0000a00d8 : 5
	fmt.Println(f2())  // 0xc0000a00d8 : 6

	fmt.Println(f1())  // 0xc0000a0090 : 6
	fmt.Println(f1())  // 0xc0000a0090 : 7
	fmt.Println(f1())  // 0xc0000a0090 : 8

}

// 定义闭包函数
func Closure() func() int {
	i := 1
	return func() int {
		fmt.Printf("%p : ", &i)
		i ++
		return i
	}
}

发布了22 篇原创文章 · 获赞 1 · 访问量 1837

猜你喜欢

转载自blog.csdn.net/weixin_42677653/article/details/105174313