On Sat, May 5, 2018 at 10:02 AM,  <[email protected]> wrote:
> I found that
>
> If a function returns interface{}
> Try to invoke it through reflect.Value.Call()
> The type of return value will be a pointer
>
> For example: (https://play.golang.org/p/gyimxUzUVYf)
> package main
>
> import (
> "fmt"
> "reflect"
> )
>
> type MyStruct struct{}
>
> func (my *MyStruct) Fn() interface{} {
> s := "aaa"
> return s
> }
>
> func main() {
>
> my := &MyStruct{}
>
> {
> m := reflect.ValueOf(my).MethodByName("Fn")
> fromReflect := m.Call([]reflect.Value{})
> fmt.Printf("fromReflect[0].Type()        = [%v] \n", fromReflect[0].Type())
> fmt.Printf("fromReflect[0].Elem().Type() = [%v] \n",
> fromReflect[0].Elem().Type())
> }
>
> {
> s := my.Fn()
> fromFunction := reflect.ValueOf(s)
> fmt.Printf("fromFunction.Type()          = [%v] \n", fromFunction.Type())
> }
> }
>
>
>
> the result is:
>
> fromReflect[0].Type()        = [interface {}]
> fromReflect[0].Elem().Type() = [string]
> fromFunction.Type()          = [string]
>
>
> I wonder why the types are different?
> I expect the result should be:
>
> fromReflect[0].Type()        = [string]
>
>
> Is this a normal behavior for reflect.Value.Call() ?

I'm not sure I understand the question.  The function returns a value
of type interface{}, and that is exactly what you see.  The interface
value holds a string type.

Note that Elem is meaningful for both pointer and interface types.
See the method docs (https://golang.org/pkg/reflect/#Value.Elem).

What may be confusing here is that when you pass an interface value to
reflect.ValueOf, you get the value that the interface holds.  That is
a consequence of how the language works.  But a reflect.Value can
still represent an interface value, and, for example, you can get that
by passing a pointer to an interface value to ValueOf, and then
calling Elem on the result.  Or, another way to get an interface value
is to do what your program does.

Iann

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to