Go - functions as values


Advertisements

Go programming language provides the flexibility to create functions on the fly and use them as values. In the following example, we've initialized a variable with a function definition. Purpose of this function variable is just to use inbuilt math.sqrt() function. For example −

package main

import ("fmt" "math")

func main(){
   /* declare a function variable */
   getSquareRoot := func(x float64) float64 {
      return math.Sqrt(x)
   }

   /* use the function */
   fmt.Println(getSquareRoot(9))
}

When the above code is compiled and executed, it produces the following result −

3
go_functions.htm
Advertisements