duanjing7459 2016-01-31 16:03
浏览 33
已采纳

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

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...

  • 写回答

2条回答 默认 最新

  • ds122455 2016-01-31 16:16
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?