英文:
How to determine if type is a struct
问题
假设我有两个结构体:
type Base struct {
    id   int
    name string
}
type Extended struct {
    Base
    Email    string
    Password string
}
我想通过反射获取Extended结构体的字段:
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).Type.Kind() != reflect.Struct {
        fmt.Println(reflect.ValueOf(e).Field(i))
    }
}
请注意,我只翻译了代码部分,其他内容不做翻译。
英文:
Suppose I have 2 structs:
type Base struct {
 id int
 name string
}
type Extended struct {
 Base
 Email string
 Password string
}
And i want to reflect the Extended struct to get it's field :
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))
  }
}
答案1
得分: 28
只需检查Value的Kind()。
if reflect.ValueOf(e).Field(i).Kind() != reflect.Struct {
    fmt.Println(reflect.ValueOf(e).Field(i))
}
请注意,这段代码是用Go语言编写的,用于检查Value的类型是否为Struct。如果不是Struct类型,将打印该Value的信息。
英文:
Just check the Kind() of Value
if reflect.ValueOf(e).Field(i).Kind() != reflect.Struct {
	fmt.Println(reflect.ValueOf(e).Field(i))
}
答案2
得分: 0
也可以使用类型开关:
switch i := x.(type) {
case nil:
	printString("x是nil")                // i的类型是x的类型(interface{})
case int:
	printInt(i)                            // i的类型是int
case float64:
	printFloat64(i)                        // i的类型是float64
case func(int) float64:
	printFunction(i)                       // i的类型是func(int) float64
case bool, string:
	printString("类型是bool或string")  // i的类型是x的类型(interface{})
default:
	printString("不知道类型")     // i的类型是x的类型(interface{})
}
英文:
Can also use type switch:
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{})
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论