[英]How to determine if type is a struct
假设我有 2 个结构:
type Base struct {
id int
name string
}
type Extended struct {
Base
Email string
Password string
}
我想反映扩展结构以获得它的字段:
e := Extended{}
e.Email = "me@mail.com"
e.Password = "secret"
for i := 0 ; i < reflect.TypeOf(e).NumField() ; i++ {
if reflect.TypeOf(e).Field(i) != "struct" { << how to do this validation?
fmt.Println(reflect.ValueOf(e).Field(i))
}
}
只需检查Value的Kind()
if reflect.ValueOf(e).Field(i).Kind() != reflect.Struct {
fmt.Println(reflect.ValueOf(e).Field(i))
}
也可以使用类型开关:
switch i := x.(type) {
case nil:
printString("x is nil") // type of i is type of x (interface{})
case int:
printInt(i) // type of i is int
case float64:
printFloat64(i) // type of i is float64
case func(int) float64:
printFunction(i) // type of i is func(int) float64
case bool, string:
printString("type is bool or string") // type of i is type of x (interface{})
default:
printString("don't know the type") // type of i is type of x (interface{})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.