Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if my interface{} is a pointer?

Tags:

go

If I have an interface being passed into a function, is there a way to tell if the item passed in is a struct or a pointer to a struct? I wrote this silly test to illustrate what I need to figure out.

type MyStruct struct {
    Value string
}

func TestInterfaceIsOrIsntPointer(t *testing.T) {
    var myStruct interface{} = MyStruct{Value: "hello1"}
    var myPointerToStruct interface{} = &MyStruct{Value: "hello1"}
    // the IsPointer method doesn't exist on interface, but I need something like this
    if myStruct.IsPointer() || !myPointerToStruct.IsPointer() { 
        t.Fatal("expected myStruct to not be pointer and myPointerToStruct to be a pointer")
    }
}
like image 733
Rob Archibald Avatar asked Jul 08 '15 06:07

Rob Archibald


1 Answers

func isStruct(i interface{}) bool {
    return reflect.ValueOf(i).Type().Kind() == reflect.Struct
}

You can test via changing type according to your needs such as reflect.Ptr. You can even get pointed value with reflect.Indirect(reflect.ValueOf(i)) after you ensured it's a pointer.

Addition:

It seems reflect.Value has a Kind method so reflect.ValueOf(i).Kind() is enough.

like image 169
ferhat Avatar answered Sep 20 '22 18:09

ferhat