簡體   English   中英

如何使用反射初始化結構值字段?

[英]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.MapToSection.MapTo方法實現了此功能。

@MuffinTop解決了您眼前的問題時,我想您可能正在解決一個錯誤的問題。 我個人至少知道兩個軟件包, github.com/Thomasdezeeuw/ini / gopkg.in/gcfg.v1 github.com/Thomasdezeeuw/inigopkg.in/gcfg.v1 ,它們能夠自動解析INI樣式的文件(各種級別的“ INI-ness”,FWIW)。使用反射來填充struct類型的值,因此對您而言,這僅相當於在結構的字段上正確設置標簽(如果需要的話)。

我在生產中都使用了這兩個軟件包,因此能夠立即推薦它們。 您可能會godoc.org找到更多專用於解析INI文件godoc.org

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM