如何确定类型是否为结构体

huangapple go评论107阅读模式
英文:

How to determine if type is a struct

问题

假设我有两个结构体:

  1. type Base struct {
  2. id int
  3. name string
  4. }
  5. type Extended struct {
  6. Base
  7. Email string
  8. Password string
  9. }

我想通过反射获取Extended结构体的字段:

  1. e := Extended{}
  2. e.Email = "me@mail.com"
  3. e.Password = "secret"
  4. for i := 0; i < reflect.TypeOf(e).NumField(); i++ {
  5. if reflect.TypeOf(e).Field(i).Type.Kind() != reflect.Struct {
  6. fmt.Println(reflect.ValueOf(e).Field(i))
  7. }
  8. }

请注意,我只翻译了代码部分,其他内容不做翻译。

英文:

Suppose I have 2 structs:

  1. type Base struct {
  2. id int
  3. name string
  4. }
  5. type Extended struct {
  6. Base
  7. Email string
  8. Password string
  9. }

And i want to reflect the Extended struct to get it's field :

  1. e := Extended{}
  2. e.Email = &quot;me@mail.com&quot;
  3. e.Password = &quot;secret&quot;
  4. for i := 0 ; i &lt; reflect.TypeOf(e).NumField() ; i++ {
  5. if reflect.TypeOf(e).Field(i) != &quot;struct&quot; { &lt;&lt; how to do this validation?
  6. fmt.Println(reflect.ValueOf(e).Field(i))
  7. }
  8. }

答案1

得分: 28

只需检查Value的Kind()。

  1. if reflect.ValueOf(e).Field(i).Kind() != reflect.Struct {
  2. fmt.Println(reflect.ValueOf(e).Field(i))
  3. }

请注意,这段代码是用Go语言编写的,用于检查Value的类型是否为Struct。如果不是Struct类型,将打印该Value的信息。

英文:

Just check the Kind() of Value

  1. if reflect.ValueOf(e).Field(i).Kind() != reflect.Struct {
  2. fmt.Println(reflect.ValueOf(e).Field(i))
  3. }

答案2

得分: 0

也可以使用类型开关:

  1. switch i := x.(type) {
  2. case nil:
  3. printString("x是nil") // i的类型是x的类型(interface{})
  4. case int:
  5. printInt(i) // i的类型是int
  6. case float64:
  7. printFloat64(i) // i的类型是float64
  8. case func(int) float64:
  9. printFunction(i) // i的类型是func(int) float64
  10. case bool, string:
  11. printString("类型是bool或string") // i的类型是x的类型(interface{})
  12. default:
  13. printString("不知道类型") // i的类型是x的类型(interface{})
  14. }
英文:

Can also use type switch:

  1. switch i := x.(type) {
  2. case nil:
  3. printString(&quot;x is nil&quot;) // type of i is type of x (interface{})
  4. case int:
  5. printInt(i) // type of i is int
  6. case float64:
  7. printFloat64(i) // type of i is float64
  8. case func(int) float64:
  9. printFunction(i) // type of i is func(int) float64
  10. case bool, string:
  11. printString(&quot;type is bool or string&quot;) // type of i is type of x (interface{})
  12. default:
  13. printString(&quot;don&#39;t know the type&quot;) // type of i is type of x (interface{})
  14. }

huangapple
  • 本文由 发表于 2017年2月6日 18:15:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/42065226.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定