动态查找结构内部内容的好方法是什么?

因此,如果我在Go中具有以下结构:</ p>

  输入Person struct {
name string
age int
}
</ code> </ pre>

鉴于我们不知道什么是 Person </ code >结构,我们如何以编程方式找出? 我四处看看,似乎可以使用反射来做到这一点?</ p>

即使只是获取struct数据的键也将是一个开始,因为类型为 [] string </ code>,但理想情况下也可以返回类型。</ p>
</ div>

展开原文

原文

So if I have the following struct in Go:

type Person struct {
    name string
    age  int
}

Given that we don't know what consists of the Person struct, how could we find out programmatically? I've had a look around and it seems that reflection could be used to do this perhaps?

Even just getting the keys for the struct data would be a start, as type []string but ideally getting the types back also would be useful.

dongliang7545
dongliang7545 到目前为止,我实际上还没有任何可发布的内容。我仍在努力尝试各种实现方法。目前处于死胡同。
6 年多之前 回复
douxunwei8259
douxunwei8259 反思更有可能是最好的方法。您能张贴您到目前为止尝试过的一些鳕鱼吗?
6 年多之前 回复

1个回答

You can indeed use reflection to do this. You primarily want reflect.TypeOf, reflect.Type.Field, reflect.Type.NumField, and reflect.StructField

Code:

package main

import "fmt"
import "reflect"

type Person struct {
    name string
    age  int
}

func main() {
    typ := reflect.TypeOf(Person{})
    for i := 0; i < typ.NumField(); i++ {
        field := typ.Field(i)
        fmt.Println("Field name:", field.Name)
        fmt.Println("Field type:", field.Type)
        fmt.Println()
    }
}

Playground link

Some notes:

  • This works for both structs in your package and out of your package
  • If you need to actually change or read data, use reflect.ValueOf and pass it a pointer to the struct, followed by a call to Value.Elem()
  • You cannot set unexported fields in another package via reflect without a panic (well, okay, you can, but it involves unsafe and ain't pretty), but you can read them. This is not recommended.
  • Always consider if you actually need reflection before you use it. At the current time, you need to have Go source to successfully import the package, so if you just need to know field names it may be better to just poke around the source code. If you need to know at runtime, ask yourself why and if there's any possible way around it. Reflect is a landmine of bugs and quirky behavior.
douyao2529
douyao2529 我的意思是说,对于很多人来说很难做到正确。 如果您了解它,它有很多行为可以使您有全面而完整的理解,但是并不能立即看出来(例如,传递指向ValueOf的指针,然后调用Elem之类的东西;处理嵌入式类型的方式也可以是一种 有点糊涂)。 我并不是在暗示反映自己是错误的或古怪的,只是如果您不知道自己在做什么,那么您可能会得到古怪的错误行为,因为您并没有真正了解它在做什么。
6 年多之前 回复
dqtl46964
dqtl46964 很好的答案,但我不同意最后一点,大多数时候不需要反射,而且反射很慢,但是如果使用正确,它既不会出错,也不会古怪。 例如,您需要json / gob / xml / mgo.bson等。
6 年多之前 回复
dousuohe5882
dousuohe5882 完美运行,似乎是一个优雅的解决方案!
6 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐