Download our all in one automation tool for various social media websites.
Functions can be used as function arguments, they can also be used as return values.
Program given below demonstrates how functions can be passed as values.
In the following program, function hello
is passed to function world
,
function world
accepts a function fn
as its argument and executes whatever
function that is passed as argument.
package main
import "fmt"
// function to print hello to console
func hello(){
fmt.Println("hello")
}
func world(fn func()){
// call whatever function that is passed as value
fn()
}
func main() {
// passing function hello as value to function world
world(hello)
}
Above program produces following output:
hello
Program given below treats functions as return value, value returned by the
function given below is then assigned to a new variable fn
and it later
executed as a function to print the massage hello
to the console.
// function being treated as return value
package main
import "fmt"
func world() func() {
// function is treated as a return value
return func() {
fmt.Println("hello")
}
}
func main() {
// get function as return value
fn := world()
// call the return value as the function
fn()
}
Above program produces following output:
hello