No, I don't think this is a duplicate of How to determine an interface{} value's "real" type?. I know how to get the Type of an interface variable, but I can't find a way to get the pointer to an interface{}'s real type.
Recently, I got into trouble with interface{}
. I have a variable with type A been passed through interface{}
, a method Tt
is defined with *A as the receiver.
I want to call the method Tt
but failed because the variable is in an interface{}
and I can't get the pointer to the variable.
As you can see, reflect.TypeOf(v)
gives the correct type A
, but reflect.TypeOf(&v)
gives *interface {}
instead of *A
.
Is there any way to get *A
?
package main
import (
"fmt"
"reflect"
)
type SomeStruct1 struct{
}
type SomeStruct2 struct{
}
type SomeStruct3 struct{
}
etc...
func (*SomeStruct1) SomeMethod(){
fmt.Println("hello")
}
func (*SomeStruct2) SomeMethod(){
fmt.Println("hello")
}
func (*SomeStruct3) SomeMethod(){
fmt.Println("hello")
}
etc...
func DoSomething(arg interface{}){
switch v:=b.(type){
[]byte:{
dosomething for []byte
}
default:{
var m reflect.Value
if value.Kind() != reflect.Ptr {
m = reflect.ValueOf(&v).MethodByName("SomeMethod")
} else {
m = reflect.ValueOf(v).MethodByName("SomeMethod")
}
m.Call(nil)
}
}
func main() {
DoSomething([]byte{...})
DoSomething(SomeStruct1{})
DoSomething(&SomeStruct1{})
etc..
}