How to Use Anonymous Functions in Golang

Created
Modified

Anonymous Function

A function literal is written like a function declaration, but without a name following the func keyword. It is an expression, and its value is called an anonymous function.

package main

import "fmt"

// squares returns a function that returns
// the next square number each time it is called.
func squares() func() int {
  var x int
  return func() int {
    x++
    return x * x
  }
}

func main() {

  f := squares()
  fmt.Println(f()) // "1"
  fmt.Println(f()) // "4"
  fmt.Println(f()) // "9"
  fmt.Println(f()) // "16"

}
$ go run main.go
1
4
9
16

Examples

Passing arguments to anonymous functions.

package main

import "fmt"

// Assigning function to the variable
var (
  area = func(i1, i2 int) int {
    return i1 * i2
  }
)

func main() {

  func(i1, i2 int) {
    fmt.Println(i1 + i2)
  }(4, 5)

  fmt.Println(area(3, 4))

}
$ go run main.go
9
12

Related Tags