Passing function pointers through channels in Go

by

in

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.


Comments

One response to “Passing function pointers through channels in Go”

  1. It is a useful pattern!
    You may be interested to know that Rob Pike mentioned this technique in his 1994 paper on Acme: http://doc.cat-v.org/plan_9/4th_edition/papers/acme/

Leave a Reply

Your email address will not be published. Required fields are marked *