Jase Whatson
Jase Whatson

Reputation: 4207

Can't get returning string value of a method called via reflection

Can't get returning string value of a method called via reflection

panic: interface conversion: interface is []reflect.Value, not string

package main

import (
        "reflect"
)

type API_EndPoint struct{}

func main() {

        var ep API_EndPoint
        s := reflect.ValueOf(&ep).MethodByName("EndPoint_X").Call([]reflect.Value{reflect.ValueOf(`foo bar`)})

        v := reflect.ValueOf(s)
        i := v.Interface()
        a := i.(string)

        println(a)

}

func (ep *API_EndPoint) EndPoint_X(params string) string {

        return "this_is_a_string" + params

}
see this code in play.golang.org

Upvotes: 0

Views: 200

Answers (1)

Datsik
Datsik

Reputation: 14824

.Call returns a slice of reflect.Value so to do what you're trying to do you need to do something like:

package main

import ("reflect")

type API_EndPoint struct {}

func main() {

var ep API_EndPoint
s := reflect.ValueOf(&ep).MethodByName("EndPoint_X").Call([]reflect.Value{reflect.ValueOf(`foo bar`)})

v := reflect.ValueOf(s)
i := v.Interface()
a := i.([]reflect.Value)[0].String() // Get the first index of the slice and call the .String() method on it

println(a) 

}

func (ep *API_EndPoint) EndPoint_X( params string) string{

        return "this_is_a_string " + params

}

https://play.golang.org/p/MtqCrshTcH

this_is_a_string foo bar

Not sure what you're trying to accomplish but that should work.

Upvotes: 2

Related Questions