1 回答

TA貢獻1887條經驗 獲得超5個贊
更新 1:我已經設法用哈希表名稱對其進行解碼。有關更多詳細信息,請參見以下示例:
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
請注意三個變化,將標簽添加到結構中,o變量指向通用結構,并使用正確的路徑打印 id ( o.fruit.Id)
這里的問題是我需要解析多個表,在標簽中指定表名是不可行的。
有沒有辦法告訴 burntsushi toml parse 忽略表名并接受其中的所有內容?就像是:
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:最后我設法獲得了包含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請注意使用to的變化toml.Decode,將結構生成到映射中fruitSpecs并在映射結構上進行交互。
這就是我解決這個問題的方法。
免費軟件。
- 1 回答
- 0 關注
- 128 瀏覽
添加回答
舉報