如何使用 reflect.Type 对 switch 进行断言

我正在使用结构库轻松迭代结构的字段,例如:


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。有可能让它以某种方式工作吗?


谢谢。


慕盖茨4494581
浏览 81回答 2
2回答

慕斯709654

您会看到该Kind()方法返回 a reflect.Kind,它是以下之一:type Kind uintconst (    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)所以你需要的案例是 likereflect.Bool而不是简单的bool.

繁星coding

使用预定义的反射类型常量:for _, field := range s.Fields() {    switch field.Kind() {    case reflect.Bool:      // do something    case reflect.String:      // do something    }  }}
打开App,查看更多内容
随时随地看视频慕课网APP