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")
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With