我正在使用 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/