jeudi 19 avril 2018

Go Reflection Panic: Call using interface{} as type

I was tinkering with reflection in Go, and I came across an interesting scenario. Can anyone explain why call1() works (returns "hello!") while call2() panics with reflect: Call using interface {} as type string? (Yes, I did already read the laws of reflection).

In the code below, the only difference between call1() and call2() is how inValue is created. I understand that the differences would have an effect on setting the value (i.e. whether or not it affects the original target), but I am not concerned with that, as I am not calling inValue.Set().

Thanks!

func main() {
    fmt.Println(call1(foo, "hello"))
    fmt.Println(call2(foo, "hello"))
}

func foo(x string) string {
    return x + "!"
}

func call1(f, x interface{}) interface{} {
    fValue := reflect.ValueOf(f)
    inValue := reflect.New(reflect.TypeOf(x)).Elem()
    inValue.Set(reflect.ValueOf(x))

    outValue := fValue.Call([]reflect.Value{inValue})[0]

    return outValue.Interface()
}

func call2(f, x interface{}) interface{} {
    fValue := reflect.ValueOf(f)
    inValue := reflect.ValueOf(&x).Elem()

    outValue := fValue.Call([]reflect.Value{inValue})[0]

    return outValue.Interface()
}





Aucun commentaire:

Enregistrer un commentaire