SoFunction
Updated on 2025-03-04

Understand Golang anonymous functions in seconds

The previous article introduced it to youUse of anonymous functions in go languageFriends who need it click to view it. Today I will introduce you to the relevant knowledge of Golang's anonymous functions. The specific content is as follows:

concept

The so-called anonymous function is a function without a name

Anonymous Functions are a type of function or subprogram that does not require defining an identifier (function name) and are widely present in many programming languages. ---wikipedia

Golang supports anonymous functions, that is, when you need to use a function, you define the function again. Anonymous functions have no function name, only function body, and the function can be assigned to a variable of the function type as a type. Anonymous functions are often passed in variable form.

Anonymous functions are often used to implement callback functions, closures, etc.

Anonymous function definition
The definition of anonymous functions is: ordinary functions without names

func (Parameter list) (Return to the value list) {
 Function body
}

Two ways to use anonymous functions

1. You can use it directly when defining anonymous functions (this method is only used once)

package main
import (
  "fmt"
)
func main(){
  res1 := func (n1 int, n2 int) int {
    return n1 + n2
  }(10, 30) //The 10 and 30 in brackets are equivalent to the parameter list, corresponding to n1 and n2 respectively  
  ("res1=",res1)
}
D:\goproject\src\main>go run 
res1= 40

2. Assign an anonymous function to a variable (function variable), and then call anonymous function through this variable.

package main
import (
  "fmt"
)
func main(){
  // Assign anonymous function fun to the variable test_fun  //The data type of test_fun is a function type, and the call can be completed through test_fun  test_fun := func (n1 int, n2 int) int {
    return n1 - n2
  }

  res2 := test_fun(10, 30)
  res3 := test_fun(50, 30)
  ("res2=", res2)
  ("res3=", res3)
  ("%T", test_fun)
}
D:\goproject\src\main>go run 
res2= -20
res3= 20
func(int, int) int

Global anonymous functions

Global anonymous function is to assign an anonymous function to a global variable, so this anonymous function can be used in the current program.

package main
import (
  "fmt"
)

//Test_fun is a well-defined global variable//Global variables must have capital lettersvar (
  Test_fun = func (n1 int, n2 int) int {
    return n1 - n2
  }
)
func main(){
  val1 := Test_fun(9, 7)

  ("val1=", val1)
}
D:\goproject\src\main>go run 
val1= 2

This is the end of this article about understanding Golang anonymous functions in seconds. For more related Golang anonymous functions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!