In Go, we can create a function without the function name, known as an anonymous function. For example,
The above function is a valid function that prints "Function without name". It works just like a regular Go Function.
Since an anonymous function doesn't have any name, you might be wondering how we can call the function.
Usually, what we do is assign the anonymous function to a variable and then use the variable name to call the function. For example,
Here, you can see that we have used the variable name greet to call the function.
Output
Here, we have assigned the anonymous function to the variable greet and used greet() to call the function.
Like a regular function, an anonymous function can also accept function parameters. For example,
Output
Here, the anonymous function takes two integer arguments n1 and n2.
Since we have assigned the anonymous function to the sum variable, we are calling the function using the variable name.
Here, 5 and 3 are values passed to the function.
Like in regular functions, we can also return a value from an anonymous function. For example,
Output
Here, we have assigned the anonymous function func(n1,n2 int) int to the sum variable. The function calculates the sum of n1 and n2 and returns it.
Output
In the above program, we have defined an anonymous function and assigned it to the variable area. The area of the rectangle, length * breadth (3 * 4), is returned to the area.
In Go, we can also pass anonymous functions as arguments to other functions. In that case, we pass the variable that contains the anonymous function. For example,
Output
In the above example, we have created two functions:
findSquare(), to find the square of a number.Notice the function call inside main()
Here, we have passed the anonymous function as the function parameter to the findSquare() function.
The anonymous function returns the sum of two parameters. This sum is then passed to the findSquare() function, which returns the square of the sum.
So, in our program, the anonymous function first returns the sum of 6 and 9, which is 15.
This value is then passed to the findSquare() function, which returns the square of 15, which is 225.
We can also return an anonymous function in Go. For that, we need to create an anonymous function inside a regular function and return it. For example,
Output
In the above program, notice this line in the displayNumber() function,
Here, the func() denotes that displayNumber() returns a function, whereas the int denotes that the anonymous function returns an integer. Notice that displayNumber() is a regular function.
Inside the displayNumber() function, we have created an anonymous function.
Here, we are returning the anonymous function. So, when the displayNumber() function is called, the anonymous function is also called and the incremented number is returned.