Anonymous Function in Golang

In Go, anonymous functions, function literals, or lambda functions are “functions without names that can be used as function values or closures”. To create an anonymous function in Golang, you can use the “func” keyword, followed by the “function parameters and return type” (if any), and the function body is enclosed in curly braces “{}”.

Example

package main

import "fmt"

func main() {
  // Define an anonymous function and assign it to a variable
  printMultiply := func(a, b int) {
    fmt.Printf("The multiplication of %d and %d is %d\n", a, b, a*b)
  }

  // Call the anonymous function using the variable
  printMultiply(2, 6)
}

Output

The multiplication of 2 and 6 is 12

In this code, we defined an anonymous function that takes two integer parameters, a and b, and prints their multiplication.

We assigned the anonymous function to a variable called printMultiply.

Finally, we called the anonymous function using the printMultiply variable and passed arguments 3 and 4.

Create closures using an anonymous function

Anonymous functions can also be used to “create closures”, which are functions that capture and reference variables from the enclosing function scope.

package main

import "fmt"

func main() {
  // Define a function that returns an anonymous function (closure)
  counter := func() func() int {
    count := 0
    return func() int {
      count++
      return count
    }
  }

  // Create a closure by calling the outer function
  mainCounter := counter()

  // Call the closure multiple times
  fmt.Println(mainCounter())
  fmt.Println(mainCounter())
  fmt.Println(mainCounter())
}

Output

1
2
3

In this code, we defined a function called “counter” that returns an anonymous function.

The anonymous function captures and references the count variable from the counter function scope.

When we call mainCounter, the closure increments the count variable and returns the updated value.

Leave a Comment