简体   繁体   中英

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.

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.

I thought the best way to achieve this might be reflection API (maybe I'm totally wrong, tell me...)

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 . The StructField has the name :

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

Note that the ini package's File.MapTo and Section.MapTo methods implement this functionality.

While @MuffinTop solved your immediate issue, I'd say you may be solving a wrong problem. 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).

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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