Go Anonymous Function

In Go, an anonymous function is a function that is declared without a name. Anonymous functions can be used in a variety of ways, including as function literals, function arguments, and function return values.

Here's an example of an anonymous function in Go:

re‮ot ref‬:theitroad.com
package main

import "fmt"

func main() {
    func() {
        fmt.Println("Hello, world!")
    }()
}

In this example, an anonymous function is declared and immediately called. The function prints the string "Hello, world!" to the console using the fmt.Println function. Note that the anonymous function is defined within another function (in this case, the main function).

Anonymous functions can also be assigned to variables, making them more flexible and reusable. Here's an example:

package main

import "fmt"

func main() {
    add := func(x, y int) int {
        return x + y
    }

    result := add(3, 4)
    fmt.Println(result) // prints "7"
}

In this example, an anonymous function that takes two integer arguments and returns their sum is assigned to a variable named add. The add variable can then be used like any other function to add two integers together.

Anonymous functions can also capture and use variables from their surrounding scope, making them a powerful tool for creating closures. Here's an example:

package main

import "fmt"

func main() {
    x := 5

    addX := func(y int) int {
        return x + y
    }

    result := addX(3)
    fmt.Println(result) // prints "8"
}

In this example, an anonymous function is used to create a closure that captures the variable x from its surrounding scope. The closure adds the value of x to an input argument y and returns the result. The closure is assigned to a variable named addX and called with an input argument of 3, resulting in a return value of 8.