匿名函数
顾名思义,就是没有名字的函数,很多语言都有,如:java, js, php, 其中js最钟情匿名函数。匿名函数最大的用途就是用来模拟块级作用域,避免数据污染。
下来,我们来看看golang的匿名函数:
- 不带参数 ```go package main
 
import ( “fmt” ) func main() { f:=func(){ fmt.Println(“hello world”) } f()//hello world fmt.Printf(“%T\n”, f) //打印 func() }
- 带参数```go// 带参数package mainimport ("fmt")func main() {f:=func(args string){fmt.Println(args)}f("hello world") // hello world}
- 带返回值 ```go package main
 
import “fmt”
func main() { f:=func()string{ return “hello world” } a:=f() fmt.Println(a) //hello world }
- 多个匿名函数```gopackage mainimport "fmt"func main() {f1,f2:=F(1,2)fmt.Println(f1(4))//6fmt.Println(f2())//6}func F(x, y int)(func(int)int,func()int) {f1 := func(z int) int {return (x + y) * z / 2}f2 := func() int {return 2 * (x + y)}return f1,f2}
闭包
闭包说白了就是函数的嵌套,内层的嵌套可以使用外层函数的所有变量,即使外层函数已经执行完毕。
package mainimport "fmt"func main() {a := Fun()d := Fun()b:=a("hello ")c:=a("hello ")e:=d("hello ")f:=d("hello ")fmt.Println(b)//worldhellofmt.Println(c)//worldhello hellofmt.Println(e)//worldhellofmt.Println(f)//worldhello hello}func Fun() func(string) string {a := "world"return func(args string) string {a += argsreturn a}}
两次调用F(), 维护的不是同一个a变量
参考:
GO 匿名函数和闭包
