例如,给出了x interface{}
。如果它是复合类型(结构或指向结构的指针)或“简单”类型,如 string
、int
、,如何确定(可能使用反射) float
等?
最佳答案
您可以使用包 reflect
, 获取其类型,并查看其 kind .如果是指针类型,则“导航”到指向的类型:
func isStruct(i interface{}) bool {
t := reflect.TypeOf(i)
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
return t.Kind() == reflect.Struct
}
测试它:
fmt.Println(isStruct("text"))
fmt.Println(isStruct(1))
fmt.Println(isStruct(image.Point{}))
fmt.Println(isStruct(&image.Point{}))
输出(在 Go Playground 上尝试):
false
false
true
true
关于go - 如何确定对象是否为复合(类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53611708/