Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




GO - LAMDA/ANONYMOUS FUNCTION


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.


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)			 	
}


Output :



 The added result is 9

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.


first_num := 5
second_num := 4

java_Collections

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.


value := add()

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'.


value := add()

And the 'Lambda' or 'Anonymous Function' is executed, adding two numbers,


result := first_num + second_num

And returning the added result.


return result

And the added result is printed.


The added result is 9