go - Golang反射: Inspect a struct type definition to extract its properties without initialization

标签 go

如果我有以下声明

type Foo struct {
   bar string
}

我可以使用反射来检查声明中的属性而不进行初始化吗?
keys := reflect.something(Foo)

for _, key := range keys {
    fmt.Println(key) // "bar"
}

最佳答案

使用reflect.TypeOf获取Foo的reflect.Type。

t := reflect.TypeOf(Foo{})

如果您不想创建该类型的值,则获取指针类型并“取消引用”该类型。
t := reflect.TypeOf((*Foo)(nil)).Elem()

表达式(*Foo)(nil)返回指向该类型的nil指针。 Type.Elem方法返回指向类型。

遍历类型上的字段。 Type.NumField返回类型的字段数。 Type.Field通过字段索引返回StructField
for i := 0; i < t.NumField; i++ {
    fmt.Println(t.Field(i).Name)
}

Run it on the playground

关于go - Golang反射: Inspect a struct type definition to extract its properties without initialization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61037457/

相关文章:

go - 使用 Kubernetes 集群 k8s 中的 SRV 记录通过 Golang 中的 DNS 实现对等发现逻辑

go - 如何针对本地文件更改更新 go doc?

go - 如何使用 gracefulStop 关闭所有 grpc 服务器流?

json - 将 Go 结构转换为 JSON

mysql - 在灵活的环境中将 Google App Engine 与 Google Cloud Storage 连接起来

go - 是否可以定义一个返回接口(interface)的无名函数?

go - 使用反射更新结构中的属性

json - Beego 发送 JSON 时跳过字段

concurrency - Goroutine 和 for 循环

go - 如何将 JSON 转换为 CSV?