Tuesday, May 14, 2019

How Function values are useful?

Golang is interesting language. If you wanna to play then start build your lego empire today. You know how to build homes, shops, trees etc. Someday, I will show you how to build a factories or companies so that our universe look like a real world. 

Like ordinary values assign to variables, in golang you can assign function values to your variables, because function values have own type.

package main
import (
"fmt"
)
func main() {
f:= square
fmt.Println(f(2))
f = underRoot
fmt.Println(f(4))
f = add
fmt.Println(f(2,2)) // error
}
func square(x int)int {
return x * x
}
func underRoot(x int)int {
return x*1/2
}
func add(x, y int)int {
return x+y
}
       Confused ?
               f = underRoot
               f = add // error
Are you confuse in these statement, if yes then square initially assign to f, which take one parameter as a argument. This tells f(2) that f hold square definition and 2 in our case value.
            4 [Ok , everything fine]
when underRoot assign to f. According to f definition , it take only one parameter as argument, which is again okay. But when add assign to f, now the compiler again check the definition of add function and compare with existing definition. In this case now whole
definition change which is not allowed. That why it produce error.

Warning :
Never return nil type value otherwise you received panic. You can't compare function values with other function value, function values are not used keys in maps.

You can also compare function value with nil. That Okay 
  

No comments:

Post a Comment

Do you support us?

Business address
0x1D24D8f27ea73ff604C7685246bdC6ae55bddaEF

Mighty Roman Empire's trail and err

  The Roman Empire's strength, fuel by economical corridor and best men's for the service but Golden days might be over when corrup...

Achieves