golang的panic: reflect: Call using int as type string

go使用动态调用方法的时候有个编译错误:

panic: reflect: Call using int as type string

在这里做个笔记,提醒自己以后要注意.
代码如下:

package main

import (
    "reflect"
    "fmt"
)

type Data struct {

}

func (*Data)Test(x,y int)(int,int)  {   //add 100
    return x + 100,y + 100
}

func (*Data)Sum(s string,x ...int) string {
    c := 0
    for _,i := range x {    //index, value
        c += i
    }
    return fmt.Sprintf(s,c)
}

func main() {
    d  := new(Data)
    v := reflect.ValueOf(d)

    exec := func(name string,in []reflect.Value) {
        m := v.MethodByName(name)
        out := m.Call(in)

        for _ , v := range out{
            fmt.Println(v.Interface())
        }
    }

    exec("Test",[]reflect.Value{
        reflect.ValueOf(1),
        reflect.ValueOf(2),
    })

    fmt.Println("---------")

    exec("Sum",[]reflect.Value{
        //报错在这里panic: reflect: Call using int as type string
        reflect.ValueOf("result = %d"), //注意要根据Sum方法签名提供参数.发生panic是因为少了这个字符串这个参数
        reflect.ValueOf(1),
        reflect.ValueOf(2),
    })
}

reflect.ValueOf("result = %d"),注意要根据Sum方法签名提供参数.发生panic是因为少了这个字符串这个参数

你可能感兴趣的:(golang)