简体   繁体   English

如何使用reflect.Type与开关键入断言

[英]How to type assert with switch using reflect.Type

I'm using the structs library to iterate easily over the fields of a struct, eg: 我正在使用结构库轻松地在结构的字段上进行迭代,例如:

package main

import "github.com/fatih/structs"

type T struct {
}

func main() {
  s := structs.New(T{})
  for _, field := range s.Fields() {
    switch field.Kind() {
    case bool:
      // do something
    case string:
      // do something
    }
  }
}

Current the code above doesn't work because of field.Kind is a reflect.Type. 当前上面的代码由于field.Kind而无法正常工作。 Is it possible to make it work somehow? 是否可以使其以某种方式工作?

Thank you. 谢谢。

You'll see that the Kind() method returns a reflect.Kind , which is one of the following: 您将看到Kind()方法返回一个reflect.Kind ,它是以下之一:

type Kind uint

const (
    Invalid Kind = iota
    Bool
    Int
    Int8
    Int16
    Int32
    Int64
    Uint
    Uint8
    Uint16
    Uint32
    Uint64
    Uintptr
    Float32
    Float64
    Complex64
    Complex128
    Array
    Chan
    Func
    Interface
    Map
    Ptr
    Slice
    String
    Struct
    UnsafePointer
)

So you'll need the cases to be like reflect.Bool instead of simply bool . 因此,您需要的情况类似于reflect.Bool而不是简单的bool

Use predefined reflect kind constants: 使用预定义的反射种类常量:

for _, field := range s.Fields() {
    switch field.Kind() {
    case reflect.Bool:
      // do something
    case reflect.String:
      // do something
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM