Passing function pointers through channels in Go

Is is possible? Of course!

package main

func add(x, y int) int {
	return x + y
}

func mul(x, y int) int {
	return x * y
}

func runner(ch chan func(int, int)(int)) {
	for f := range ch {
		println("f(1, 2) = ", f(1, 2))
	}
}

func main() {
	ch := make(chan func(int, int)(int))
	go runner(ch)

	ch <- add
	ch <- mul
	ch <- add
	close(ch)
}

Is it useful? Probably, but this demo doesn't show how yet... have to think about what patterns this makes possible.

One thought on “Passing function pointers through channels in Go

Leave a Reply