Anonymous functions are especially useful in cases where you want to encapsulate functionality without polluting the global namespace or when using function literals in higher-order functions.
Example 1: Storing an Anonymous Function in a Variable
In this example, we declare an anonymous function inside themain function. The function takes two integers as parameters and returns their product. Notice that there is no name for the function since it is anonymous; instead, it is assigned directly to the variable x.
go run main.go, you will see the following output:
x is a function taking two integers and returning an integer. The call x(20, 30) computes the product, resulting in 600.
Example 2: Directly Invoking an Anonymous Function
Here, the anonymous function is defined and invoked immediately without being stored in a variable. The function is executed with the provided arguments (20 and 30), and its result is directly assigned tox. Since the function returns an integer value (600), the type of x is int.
x directly holds the result of the function call, emphasizing how you can use anonymous functions for immediate operations.