[英]How to initialize a struct value fields using reflection?
我得到了一个.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
}
任何帮助表示赞赏...
使用类型 获取StructField 。 StructField的名称为 :
name := value.Type().Field(i).Name
请注意,ini包的File.MapTo和Section.MapTo方法实现了此功能。
@MuffinTop解决了您眼前的问题时,我想您可能正在解决一个错误的问题。 我个人至少知道两个软件包, github.com/Thomasdezeeuw/ini
/ gopkg.in/gcfg.v1
github.com/Thomasdezeeuw/ini
和gopkg.in/gcfg.v1
,它们能够自动解析INI样式的文件(各种级别的“ INI-ness”,FWIW)。使用反射来填充struct
类型的值,因此对您而言,这仅相当于在结构的字段上正确设置标签(如果需要的话)。
我在生产中都使用了这两个软件包,因此能够立即推荐它们。 您可能会在godoc.org
上找到更多专用于解析INI文件的godoc.org
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.