1 回答

TA貢獻(xiàn)1887條經(jīng)驗(yàn) 獲得超5個(gè)贊
更新 1:我已經(jīng)設(shè)法用哈希表名稱對(duì)其進(jìn)行解碼。有關(guān)更多詳細(xì)信息,請(qǐng)參見(jiàn)以下示例:
type (
fruitSpecs struct {
Id int `toml:"id"`
Name string `toml:"name"`
}
fruits struct {
fruit fruitSpecs `toml:"kiwi"`
}
)
blob := `
[kiwi]
id = 1234581941
name = "kiwi"
`
o := &fruits{}
err := toml.Unmarshal([]byte(blob), o)
fmt.Println(o.fruit.Id)
// CLI Output:
// 1234581941
請(qǐng)注意三個(gè)變化,將標(biāo)簽添加到結(jié)構(gòu)中,o變量指向通用結(jié)構(gòu),并使用正確的路徑打印 id ( o.fruit.Id)
這里的問(wèn)題是我需要解析多個(gè)表,在標(biāo)簽中指定表名是不可行的。
有沒(méi)有辦法告訴 burntsushi toml parse 忽略表名并接受其中的所有內(nèi)容?就像是:
type (
fruitSpecs struct {
Id int `toml:"id"`
Name string `toml:"name"`
}
fruits struct {
fruit fruitSpecs `toml:"*"` // Do not filter by name, accept every table name entry
}
)
blob := `
[kiwi]
id = 1234581941
name = "kiwi"
[banana]
id = 9876544312
name = "banana"
`
o := &fruits{}
err := toml.Unmarshal([]byte(blob), o)
fmt.Println(o.fruit.Id)
// Desired output:
// 1234581941
// 9876544312
更新 2:最后我設(shè)法獲得了包含Id以下代碼的所有字段:
type (
fruitSpecs struct {
Id int `toml:"id"`
Name string `toml:"name"`
}
fruit map[inteface{}]fruitSpecs
)
blob := `
[kiwi]
id = 1234581941
name = "kiwi"
[banana]
id = 9876544312
name = "banana"
`
var o fruit
err := toml.Decode(blob, &fruit)
for _, item := range o {
fmt.Println(item.Id)
}
// CLI Output:
// 1234581941
// 9876544312
toml.Unmarshall請(qǐng)注意使用to的變化toml.Decode,將結(jié)構(gòu)生成到映射中fruitSpecs并在映射結(jié)構(gòu)上進(jìn)行交互。
這就是我解決這個(gè)問(wèn)題的方法。
免費(fèi)軟件。
- 1 回答
- 0 關(guān)注
- 125 瀏覽
添加回答
舉報(bào)