【问题标题】:How to determine if type is a struct如何确定类型是否为结构
【发布时间】:2017-06-23 05:51:00
【问题描述】:

假设我有 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))
  }
}

【问题讨论】:

标签: go reflection struct


【解决方案1】:

只需检查值的 Kind()

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

【讨论】:

  • 似乎不需要使用 Type,因为 Value 本身也有 Kind()。
猜你喜欢
  • 2011-02-12
  • 1970-01-01
  • 2011-06-11
  • 1970-01-01
  • 2011-01-18
  • 1970-01-01
  • 2010-10-29
  • 2021-12-16
  • 2010-12-11
相关资源
最近更新 更多