Golang 匿名函数
Go语言提供了一个特殊的功能,即匿名函数。匿名函数是一个不包含任何名称的函数。当你想创建一个内联函数时,它很有用。在Go语言中,匿名函数可以形成一个闭包。一个匿名函数也被称为 函数字面。
语法
func(parameter_list)(return_type){
// code..
// Use return statement if return_type are given
// if return_type is not given, then do not
// use return statement
return
}()
例子
// Go program to illustrate how
// to create an anonymous function
package main
import "fmt"
func main() {
// Anonymous function
func(){
fmt.Println("Welcome! to GeeksforGeeks")
}()
}
输出
Welcome! to GeeksforGeeks
重要观点
- 在Go语言中,你可以将匿名函数分配给一个变量。当你把一个函数赋值给一个变量时,那么这个变量的类型就是函数类型,你可以像调用函数一样调用这个变量,如下例所示。
示例:
// Go program to illustrate
// use of an anonymous function
package main
import "fmt"
func main() {
// Assigning an anonymous
// function to a variable
value := func(){
fmt.Println("Welcome! to GeeksforGeeks")
}
value()
}
输出:
Welcome! to GeeksforGeeks
- 你也可以在匿名函数中传递参数。
示例:
// Go program to pass arguments
// in the anonymous function
package main
import "fmt"
func main() {
// Passing arguments in anonymous function
func(ele string){
fmt.Println(ele)
}("GeeksforGeeks")
}
输出:
GeeksforGeeks
- 你也可以将一个匿名函数作为参数传递给其他函数。
示例:
// Go program to pass an anonymous
// function as an argument into
// other function
package main
import "fmt"
// Passing anonymous function
// as an argument
func GFG(i func(p, q string)string){
fmt.Println(i ("Geeks", "for"))
}
func main() {
value:= func(p, q string) string{
return p + q + "Geeks"
}
GFG(value)
}
输出:
GeeksforGeeks
- 你也可以从另一个函数中返回一个匿名函数。
示例:
// Go program to illustrate
// use of anonymous function
package main
import "fmt"
// Returning anonymous function
func GFG() func(i, j string) string{
myf := func(i, j string)string{
return i + j + "GeeksforGeeks"
}
return myf
}
func main() {
value := GFG()
fmt.Println(value("Welcome ", "to "))
}
输出:
Welcome to GeeksforGeeks