【问题标题】:How to type assert with switch using reflect.Type如何使用 reflect.Type 使用 switch 键入断言
【发布时间】:2019-05-23 15:05:16
【问题描述】:

我正在使用structs 库轻松地遍历结构的字段,例如:

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
    }
  }
}

目前上面的代码不起作用,因为 field.Kind 是一个 reflect.Type。有没有可能让它以某种方式工作?

谢谢。

【问题讨论】:

    标签: go struct types


    【解决方案1】:

    使用预定义的反射种类常量:

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

    【讨论】:

      【解决方案2】:

      您会看到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
      )
      

      因此,您需要像 reflect.Bool 而不是简单的 bool。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-02
        • 1970-01-01
        • 2012-10-04
        • 1970-01-01
        • 2021-04-06
        • 1970-01-01
        • 1970-01-01
        • 2013-09-03
        相关资源
        最近更新 更多