A 'Lambda' or 'Anonymous Function' is a small function that can just have a small expression and doesn't have a name.
Let us write a normal 'Function' that adds two numbers and returns the result.
func add(first_number int, second_number int) { result := first_number + second_number return result }
Now, let us write, exactly same 'Lambda' or 'Anonymous Function' for the above 'add' Function in the below example.
package main import "fmt" func main() { first_num := 5 second_num := 4 add := func() (int) { result := first_num + second_num return result } value := add() fmt.Println("The added value is :",value) }
So, in the above code, we have defined a function that has no name. And most importantly,we have defined the 'Anonymous Function' inside the 'main()' method.
add := func() (int) { result := first_num + second_num return result }
Now, the question is, how the 'Anonymous Function' can access the variables, 'first_num' and 'second_num'?
Well! Since the 'Anonymous Function' is defined inside the 'main()' function. It will have access to all the variables inside the 'main()' function.
So, we have the variables, 'first_num' and 'second_num' inside the 'main()' function.
And in the next line, we have the 'Lambda' or 'Anonymous Function' defined.
But hold on! It will not get executed until it is called. But it doesn't have a name, how do we call it?
Now, if you see the next line, the 'Anonymous Function' is actually called.
With the name 'add()'.
And what's 'add()'?
If you see the 'Anonymous Function'.
add := func() (int) { result := first_num + second_num return result }
It has the variable 'add' that contains the returned result of the 'Anonymous Function'. And we have used that 'add' with parenthesis '()' to call the 'Anonymous Function'.
And the 'Lambda' or 'Anonymous Function' is executed, adding two numbers,
And returning the added result.
And the added result is printed.