Anonymous function in Go

In Go, an anonymous function is a function that doesn’t have a name. Instead of defining it with a specific name, you create the function directly inline and assign it to a variable, or you can directly use it as an argument to another function. Anonymous functions are also known as lambda functions or function literals.

The basic syntax of an anonymous function in Go is as follows:

func(parameters) returnType {
    // Function body - code that performs the task
    // Return statement (if applicable)
}

Here are some key points about anonymous functions in Go:

  • Anonymous functions are defined without a function name and are created as function values that can be assigned to variables.
  • They can be used to create closures, which means they can capture and access variables from the surrounding scope.
  • Anonymous functions are commonly used in situations where a small function is needed for a specific task, and it’s more convenient to define the function inline.

Example of using an anonymous function:

package main

import "fmt"

func main() {
    // Anonymous function assigned to a variable
    add := func(a, b int) int {
        return a + b
    }

    result := add(10, 5)
    fmt.Println("Result:", result)

    // Anonymous function directly used as an argument
    func(message string) {
        fmt.Println("Hello", message)
    }("World")
}

Output :

Result: 15
Hello World

In this example, we define an anonymous function and assign it to a variable named add. The function takes two integer parameters a and b and returns their sum. We then call the anonymous function using the variable add.

Next, we use another anonymous function directly as an argument to the fmt.Println function. This anonymous function takes a string parameter message and prints “Hello” followed by the message.

Anonymous functions are useful when you need a small, one-off function that doesn’t require a named definition. They offer a concise and efficient way to create functions inline, making the code more readable and expressive. Additionally, the ability to create closures with anonymous functions enables powerful and flexible programming in Go.

Here’s another example of using an anonymous function in Go:

package main

import "fmt"

func main() {
    // Anonymous function as a closure
    counter := func() func() int {
        count := 0
        return func() int {
            count++
            return count
        }
    }()

    fmt.Println("Counter Value:", counter())
    fmt.Println("Counter Value:", counter())
    fmt.Println("Counter Value:", counter())
}

Output :

Counter Value: 1
Counter Value: 2
Counter Value: 3

In this example, we define an anonymous function that acts as a closure. A closure is a function value that references variables from outside its body. In this case, the outer anonymous function returns an inner anonymous function.

The inner anonymous function maintains its own local variable count, which is initialized to 0. Every time the inner function is called, it increments the count and returns its updated value. The count variable’s value is preserved between function calls because of the closure.

In the main function, we call the outer anonymous function and assign its result to the variable counter. Now, counter holds the inner function, and we can call it multiple times to increment and retrieve the counter value.

Anonymous functions as closures are powerful for creating encapsulated and self-contained behavior within your code. They allow you to maintain state across function calls and create reusable code patterns without the need for additional named functions.