Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting a function from a list of functions in Golang

Basically if I have a slice or array of any arbitrary functions, how can I select only the ones that return int, or select only the ones that take ints?

I figured that I would need to use the reflect package, but just reading the docs didn't really help me figure out exactly how to do it.

like image 666
placeybordeaux Avatar asked Sep 17 '12 15:09

placeybordeaux


1 Answers

This program prints the functions taking an int as parameter or returning an int :

package main

import (
    "fmt"
    "reflect"
)

func main() {
    funcs := make([]interface{}, 3, 3) // I use interface{} to allow any kind of func
    funcs[0] = func (a int) (int) { return a+1} // good
    funcs[1] = func (a string) (int) { return len(a)} // good
    funcs[2] = func (a string) (string) { return ":("} // bad
    for _, fi := range funcs {
        f := reflect.ValueOf(fi)
        functype := f.Type()
        good := false
        for i:=0; i<functype.NumIn(); i++ {
            if "int"==functype.In(i).String() {
                good = true // yes, there is an int among inputs
                break
            }
        }
        for i:=0; i<functype.NumOut(); i++ {
            if "int"==functype.Out(i).String() {
                good = true // yes, there is an int among outputs
                break
            }
        }
        if good {
            fmt.Println(f)
        }
    }
}

I think the code is self explanatory

like image 168
Denys Séguret Avatar answered Dec 09 '22 19:12

Denys Séguret