dongyuedaochen8415 2014-04-22 10:38
浏览 36
已采纳

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

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.

  • 写回答

1条回答 默认 最新

  • douhuanchi6586 2014-04-22 10:54
    关注

    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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?