dscc90150010 2015-07-08 06:54
浏览 210
已采纳

如何判断我的interface {}是否是指针?

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")
    }
}
  • 写回答

3条回答 默认 最新

  • doujiao3346 2015-07-08 07:10
    关注
    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?