简体   繁体   English

如何使用反射初始化结构值字段?

[英]How to initialize a struct value fields using reflection?

I got a .ini configuration file that I want to use to initialize a Configuration struct. 我得到了一个.ini配置文件,该文件用于初始化Configuration结构。

I'd like to use the Configuration fields names and loop over them to populate my new instance with the corresponding value in the .ini file. 我想使用“ Configuration字段名称并在其上循环,以.ini文件中的相应值填充新实例。

I thought the best way to achieve this might be reflection API (maybe I'm totally wrong, tell me...) 我认为实现此目标的最佳方法可能是反射API(也许我完全错了,告诉我...)

My problem here is that I cannot figure out how to access field's name (if it is at least possible) 我的问题是我无法弄清楚如何访问字段名称(如果至少可以)

Here is my code: 这是我的代码:

package test
import(
     "reflect"
     "gopkg.in/ini.v1"
 )

type Config struct {
    certPath string
    keyPath  string
    caPath   string
}

func InitConfig(iniConf *ini.File) *Config{
    config:=new(Config)
    var valuePtr reflect.Value = reflect.ValueOf(config)
    var value reflect.Value = valuePtr.Elem()
    for i := 0; i < value.NumField(); i++ {
        field := value.Field(i)
        if field.Type() == reflect.TypeOf("") {
            //here is my problem, I can't get the field name, this method does not exist... :'(
            value:=cfg.GetSection("section").GetKey(field.GetName())
            field.SetString(value)
        }
    }
    return config
}

Any help appreciated... 任何帮助表示赞赏...

Use the type to get a StructField . 使用类型 获取StructField The StructField has the name : StructField的名称为

 name := value.Type().Field(i).Name

Note that the ini package's File.MapTo and Section.MapTo methods implement this functionality. 请注意,ini包的File.MapToSection.MapTo方法实现了此功能。

While @MuffinTop solved your immediate issue, I'd say you may be solving a wrong problem. @MuffinTop解决了您眼前的问题时,我想您可能正在解决一个错误的问题。 I personally know of at least two packages, github.com/Thomasdezeeuw/ini and gopkg.in/gcfg.v1 , which are able to parse INI-style files (of the various level of "INI-ness", FWIW) and automatically populate your struct -typed values using reflection, so for you it merely amounts to properly setting tags on the fields of your struct (if needed at all). 我个人至少知道两个软件包, github.com/Thomasdezeeuw/ini / gopkg.in/gcfg.v1 github.com/Thomasdezeeuw/inigopkg.in/gcfg.v1 ,它们能够自动解析INI样式的文件(各种级别的“ INI-ness”,FWIW)。使用反射来填充struct类型的值,因此对您而言,这仅相当于在结构的字段上正确设置标签(如果需要的话)。

I used both of these packages in production so am able to immediately recommend them. 我在生产中都使用了这两个软件包,因此能够立即推荐它们。 You might find more packages dedicated to parsing INI files on godoc.org . 您可能会godoc.org找到更多专用于解析INI文件godoc.org

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM