Golang Tutorial

Fundamentals

Control Statements

Functions & Methods

Structure

Arrays & Slices

String

Pointers

Interfaces

Concurrency

Anonymous Function in Golang

Anonymous functions in Go (often called "lambda functions" in other languages) are functions without a name. They can be used inline and you don't need to define a standard function to use them.

Here are the steps to create and use an anonymous function in Go:

1. Basic Anonymous Function

This example demonstrates a basic anonymous function in Go:

package main

import "fmt"

func main() {
    func() {
        fmt.Println("This is an anonymous function.")
    }()
}

In this example, the function is defined and immediately invoked. The () at the end of the function definition is used to invoke the function.

2. Anonymous Function with Parameters

You can also pass parameters to an anonymous function:

package main

import "fmt"

func main() {
    func(name string) {
        fmt.Println("Hello,", name)
    }("John")
}

3. Assigning Anonymous Function to a Variable

You can assign an anonymous function to a variable and then call it:

package main

import "fmt"

func main() {
    greet := func(name string) {
        fmt.Println("Hello,", name)
    }

    greet("Alice")
    greet("Bob")
}

4. Returning Anonymous Functions

Functions can also return anonymous functions:

package main

import "fmt"

func multiplier(factor int) func(int) int {
    return func(num int) int {
        return num * factor
    }
}

func main() {
    double := multiplier(2)
    fmt.Println(double(5)) // Outputs: 10

    triple := multiplier(3)
    fmt.Println(triple(5)) // Outputs: 15
}

In the above example, the multiplier function returns an anonymous function which, when invoked, multiplies its argument by the factor specified when creating the function.

5. Anonymous Functions as Closure

Anonymous functions can access and modify variables from the outer function. Such functions are called closures:

package main

import "fmt"

func counter() func() int {
    count := 0
    return func() int {
        count++
        return count
    }
}

func main() {
    next := counter()
    fmt.Println(next()) // Outputs: 1
    fmt.Println(next()) // Outputs: 2
    fmt.Println(next()) // Outputs: 3
}

In this example, the counter function returns an anonymous function that serves as a closure over the count variable. Each time the returned function is called, the count increases.

Conclusion

Anonymous functions in Go are quite versatile and can be utilized in various ways: as inline functions, closures, or functional arguments. They are especially useful when you want a short-lived function, for instance, as a one-off for a goroutine or when using functions like sort.Slice with custom comparators.

  1. Closure in Golang:

    • A closure in Go is a function value that references variables from outside its body. It can access and modify the variables it captures.
    • Example:
      func closureExample() func() int {
          i := 0
          return func() int {
              i++
              return i
          }
      }
      
  2. Golang Anonymous Function Examples:

    • Anonymous functions in Go are functions without a name. They are often used for short-lived or one-time operations.
    • Example:
      func main() {
          add := func(a, b int) int {
              return a + b
          }
          result := add(3, 5)
          fmt.Println(result) // Output: 8
      }
      
  3. Function Literals in Go:

    • Function literals are anonymous functions defined directly within an expression.
    • Example:
      func main() {
          result := func(a, b int) int {
              return a * b
          }(3, 4)
          fmt.Println(result) // Output: 12
      }
      
  4. Golang Anonymous Function vs Named Function:

    • Named functions have a declared name and can be called from anywhere in the package. Anonymous functions are declared inline.
    • Example:
      // Named function
      func add(a, b int) int {
          return a + b
      }
      
      // Anonymous function
      addAnonymous := func(a, b int) int {
          return a + b
      }
      
  5. Anonymous Functions and Variables in Golang:

    • Anonymous functions can capture and manipulate variables from their surrounding scope.
    • Example:
      func main() {
          x := 10
          increment := func() {
              x++
          }
          increment()
          fmt.Println(x) // Output: 11
      }
      
  6. Using Anonymous Functions in Golang Callbacks:

    • Anonymous functions are commonly used as callbacks, passing them as arguments to other functions.
    • Example:
      func process(nums []int, callback func(int) int) {
          for i, v := range nums {
              nums[i] = callback(v)
          }
      }
      
  7. Golang Higher-Order Functions with Anonymous Functions:

    • Higher-order functions in Go can take functions as parameters or return functions as results.
    • Example:
      func multiplyBy(factor int) func(int) int {
          return func(x int) int {
              return x * factor
          }
      }
      
  8. Capturing Variables in Golang Closures:

    • Closures capture variables from their surrounding lexical scope, allowing them to retain and modify the values.
    • Example:
      func closureExample() func() int {
          i := 0
          return func() int {
              i++
              return i
          }
      }