Foreword: I
learned the anonymous function of go language today and found it very interesting. Record it here so that I can forget to search it later.
Anonymous function: As the name implies, it is a function without a name. Many languages are like: java, js, php, etc., of which js is the most favorite. The biggest use of anonymous functions is to simulate block-level scope to avoid data pollution.
1. Define an anonymous function outside the function
var f01 = func() {
fmt.Println("匿名函数")
}
func main(){
f01()
}
2. Anonymous functions are defined inside the function
There are two types here: ordinary anonymous functions, and one is an anonymous function that can be executed immediately, and is called only once.
2.1 Common anonymous functions
func main(){
f1 := func() {
fmt.Println("内部匿名函数")
}
f1()
}
2.2 Anonymous functions for immediate execution
func main(){
//立即执行匿名函数
func(x,y int){
fmt.Println(x+y)
}(10,20)
}
3. Summary
The use of anonymous functions is still very interesting, here is just an example of a simple method of use, the specific use of development still needs to think for yourself.