I have this function that accepts an interface{}
func MyFunk(itf interface{}) {
}
And I would like to know if the itf passed is a struct, is that possible? I've tried several combinations of reflect, and the closes that I could get was ptr
(pointer).
Use the following to detect if the argument is a struct:
func MyFunk(itf interface{}) {
v := reflect.ValueOf(itf)
if v.Kind() == reflect.Struct {
// it's a struct
}
}
If you also want to check for pointers to structs, then use this code:
func MyFunk(itf interface{}) {
v := reflect.Indirect(reflect.ValueOf(itf))
if v.Kind() == reflect.Struct {
// it's a struct
}
}
May be Type assertions can help you
func MyFunk(itf interface{}) {
s, ok := itf.(MyStruct)
fmt.Println(s, ok)
}
Using the reflect
package, you can check for both struct types and pointers to structs:
func MyFunk(itf interface{}) {
t := reflect.TypeOf(itf)
if t.Kind() == reflect.Struct {
// itf is a struct
} else if t.Kind() == reflect.Ptr {
pt := t.Elem()
if pt.Kind() == reflect.Struct {
// itf is a pointer to a struct
} else {
// itf is a pointer to something else
}
} else {
// itf is something else entirely
}
}