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

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

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 = &quot;me@mail.com&quot;
e.Password = &quot;secret&quot;

for i := 0 ; i &lt; reflect.TypeOf(e).NumField() ; i++ {
  if reflect.TypeOf(e).Field(i) != &quot;struct&quot; {  &lt;&lt; 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(&quot;x is nil&quot;)                // 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(&quot;type is bool or string&quot;)  // type of i is type of x (interface{})
default:
	printString(&quot;don&#39;t know the type&quot;)     // type of i is type of x (interface{})
}

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:

确定