Gopher

Passing functions as values in Golang

Published on 29 March 2020
Last Updated on 29 March 2020

Functions can be used as function arguments, they can also be used as return values.

Program to pass functions as 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)
}

Program output

Above program produces following output:

hello

Program that treats functions as return values

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

Program output

Above program produces following output:

hello