Gaaker Go

Golang Function as parameters

The function is a value type, so it can be passed as a parameter.

The following is a complete code example.

package main

import (
	"fmt"
)

func plusWithCallback(a int, b int, callback func(c int)) {
    c := a + b
    callback(c);
}

func printResult(c int)  {
	fmt.Println("a + b = ", c)
}

func main() {
	plusWithCallback(1, 1, func (c int)  {
        fmt.Println("a + b = ", c)
    })
	plusWithCallback(2, 2, printResult)
}

Below is the program output:

a + b =  2
a + b =  4
< Function as parameters Function as parameters >