Call back function

I am messing around trying to understand callback functions. I have used them in JS before for event listeners, but for some reason in Go (it may be because of the type needing specification i am not sure), but i am having trouble having it resonate. I can create simple CallBack like.

package main

import (
    "fmt"
)

func main() {
    run(example)
}

func example() {
    fmt.Println(2 + 2)
}



func run(f func()) {
    f()
}

but when i try to do this in another way all hell breaks loose.

package main

import "fmt"

func main() {
	total := run(example, 2, 2)
	fmt.Println(total)

}

func example(a int, b int) int {
	return a + b
}

func run(f func(a int, b int), a int, b int) int {
	f()
	return f()
}

Can someone please help me understand this from a different perspective other than the Pig example from the Go documentation?

  1. You need to pass a and b to f(): f(a, b)
  2. Type of example() is func(int, int)int not func(int,int), when you declare the type of an argument, the return value has to fit as well
  3. You are trying to return the result of a function that isn’t expected to return anything when Go expects you to return an int.
3 Likes