Golang 匿名函数

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

例子

// Go program to illustrate how
// to create an anonymous function
package main
  
import "fmt"
  
func main() {
      
    // Anonymous function
   func(){
  
      fmt.Println("Welcome! to GeeksforGeeks")
  }()
    
}
Go

输出

Welcome! to GeeksforGeeks
Go

重要观点

  • 在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()
        
    }
Go

输出:

Welcome! to GeeksforGeeks
Go
  • 你也可以在匿名函数中传递参数。

示例:

// 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")
    
}
Go

输出:

GeeksforGeeks
Go
  • 你也可以将一个匿名函数作为参数传递给其他函数。

示例:

// 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)
}
Go

输出:

GeeksforGeeks
Go
  • 你也可以从另一个函数中返回一个匿名函数。

示例:

// 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 "))
}
Go

输出:

Welcome to GeeksforGeeks
Go

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册