Anonymous Functions are functions without any specific name assigned to it. They are usually used once only that’s why assigning a name may not be so much useful.

Anonymous functions look and behave same as normal functions, in that they can input arguments and return some output. Anonymous functins are also called function literal. This is one of the fundamental feature of any functional programming language. Go does support functional programming with built-in features.

Defining Anonymous Functions

These are defined using below syntax.

1func function_name(parameters) (return_type) {
2    // statements
3}

At first time, this syntax may look awkward but you will get used to this as you use them more often.

Example:

1package main
2
3import "fmt"
4
5func main() {
6	func() {
7		fmt.Println("Hello")
8	}()
9}

Here, we defined a function inside our main function on line 6. However, this function does not have any name. Also interesting thing is that after the definition of the function, we are right away calling this function using pair of parentheses on line 8.

Output:

Hello

Anonymous Function with Parameters

Anonymous functions can take parameters which can be used inside the function.

 1package main
 2
 3import "fmt"
 4
 5func main() {
 6	sum := func(a int, b int) int {
 7		return a + b
 8	}(10, 20)
 9	fmt.Printf("%d\n", sum) // 5
10}

Here, we defined a function which takes two arguments and returns the sum of those two numbers.

Output:

30

Interestingly, we can also assign anonymous function to a variable. The data type of that variable will be same as the signature of the function.

Example:

 1package main
 2
 3import "fmt"
 4
 5func main() {
 6	output := func(a int, b int) int {
 7		return a + b
 8	}
 9	fmt.Printf("%T\n", output)       // func(int, int) int
10	fmt.Printf("%d\n", output(2, 3)) // 5
11}

In this case, we assign the function to a variable output. We can treat this variable as a function.

Output:

func(int, int) int
5

We can also return an anonymous function as a value from another function.

Example:

 1package main
 2
 3import "fmt"
 4
 5func main() {
 6	sum_function := adder(2, 3)
 7	fmt.Println(sum_function())
 8	sum_function = adder(10, 10)
 9	fmt.Println(sum_function())
10}
11
12func adder(a int, b int) func() int {
13	sum_fn := func() int {
14		return a + b
15	}
16	return sum_fn
17}

In this case, from adder function definition, we return another function sum_fn which does addition of two int values.

Output:

5
20