Golang - How do you create a slice of functions with different signatures?

后端 未结 2 1084
旧时难觅i
旧时难觅i 2021-01-18 01:01

How do you create a slice of functions with different signatures? I tried the code below but its feels hack-ish. Do we just bite the bullet and use a slice interface{}?

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-18 02:04

    Please check it, I don't know if it what you want. Because I don't know what are you exactly want.

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    func A() {
        fmt.Println("A")
    }
    
    func B(A int) {
        fmt.Println("B", A)
    }
    
    func C(A string, B float32) {
        fmt.Println("C", A, B)
    }
    
    func main() {
        f := []interface{}{A, B, C}
        f[0].(func())()
        f[1].(func(int))(15)
        f[2].(func(string, float32))("TEST", 90)
    
        fmt.Println("\n******* another thing ******")
        for a, v := range f {
            v := reflect.TypeOf(v)
            fmt.Println("#######", a)
            fmt.Println("num param :", v.NumIn())
            for i := 0; i < v.NumIn(); i++ {
                fmt.Println("param :", i, "type is ", v.In(i))
            }
        }
    }
    

    Check on Go Playground

    Here I have another example calling using reflect

    package main
    
        import (
            "fmt"
            "reflect"
        )
    
        func A() {
            fmt.Println("A")
        }
    
        func B(A int) {
            fmt.Println("B", A)
        }
    
        func C(A string, B float32) {
            fmt.Println("C", A, B)
        }
    
        func main() {
            f := []interface{}{A, B, C}
            f[0].(func())()
            f[1].(func(int))(15)
            f[2].(func(string, float32))("TEST", 90)
    
            fmt.Println("\n******* calling with reflect ******")
            for a, v := range f {
                v := reflect.TypeOf(v)
                //calling the function from reflect
                val := reflect.ValueOf(f[a])
                params := make([]reflect.Value, v.NumIn())
                if v.NumIn() == 1 {
                    params[0] = reflect.ValueOf(1564)
                } else if v.NumIn() == 2 {
                    params[0] = reflect.ValueOf("Test FROM reflect")
                    params[1] = reflect.ValueOf(float32(123456))
                }
                val.Call(params)
            }
        }
    

    Check on Go Playground

提交回复
热议问题