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

标签 go struct types

我正在使用 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。有没有可能让它以某种方式工作?

谢谢。

最佳答案

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

关于go - 如何使用 reflect.Type 对 switch 进行断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53913629/

相关文章:

user-interface - 在 Goland IDE 中运行 GUI 应用程序

go - 在 golang 中创建一个返回类型为 imagemagick 对象的函数

转到模块 : checksum mismatch

将字符串复制到结构体 C 中

c++ - 如何通过先前存储的 ID 从结构对象中检索值? C++

pointers - Go struct literals,为什么这个是可寻址的?

c - C语言中位域的实际用途是什么?

haskell - 编程语言中“缺少”(?)功能?

mysql - BOOLEAN 或 TINYINT 混淆

c - 在 C 中存储微秒总和的正确数据类型是什么