Function as Parameters in Golang

Aman Agarwal
2 min readMay 29, 2021

--

Being a Software Developer don’t you think that we should pass a function as a parameter to another function !! OOh, we always want that, when it comes to applying any functionality with optional functionality which we need to add up to the parent functionality.
You can think it about like a Parent class with multiple child classes and all are different with themselves.

If we go for a Simple real-life example we can talk about a restaurant where they give Rice with whatever else you want with it from options (curd, fish, chicken, Dal ) but only one. So Some can take chicken other may choose dal. In this kind of scenario where we a functionality Rice with additional optional functionality other dishes.

How Can we solve this!
We can define a function that adds Rice to our plate, and another function as a parameter to this function which tells the sub-dish we want to add with rice.
Okay, we are done with reading let’s go for some tic-tic code…

package mainimport "fmt"func main() {
plate(chiken, "rice")
plate(dal, "rice")
}
func plate(f func() string, primaryDish string) {
fmt.Println("This Plate Will Have - " + primaryDish + f())
}
func chiken() string {
return " with Chiken" //This Plate Will Have - rice with Chiken
}
func dal() string {
return " with Dal" //This Plate Will Have - rice with Dal
}

You can run it from here.

In the above code, we added our sub dish with a primary dish to the plate.

But Now the interesting thought besides passing a function as an argument .Can a function return another function as a return value.

The answer is yes let see it with another code …

package mainimport "fmt"func plate(primaryDish string) func(param string) {
// function is treated as a return value
return func(param string) {
fmt.Println("This plate Will have - " + primaryDish + param)
}
}
func main() {
// get function as return value
fn := plate("rice")
// call the return value as the function
fn(" with chiken")
fn(" with fish")
}

You can run it from here.

In the Above example, we can call the sub-function as many times as we want with the same primary function functionality.

--

--

Aman Agarwal
Aman Agarwal

Written by Aman Agarwal

Engineer | Explorer | Blockchain | Golang | JavaScript developer

No responses yet