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

n00dl3:

我有一个.ini要用于初始化Configuration结构配置文件

我想使用Configuration字段名称并遍历它们,以.ini文件中的相应值填充新实例。

我认为实现此目标的最佳方法可能是反射API(也许我完全错了,告诉我...)

我的问题是我无法弄清楚如何访问字段名称(如果至少可以)

这是我的代码:

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
}

任何帮助表示赞赏...

松饼上衣:

使用类型,以获得StructFieldStructField的名称为

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

请注意,ini包的File.MapToSection.MapTo方法实现了此功能。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章