使用 toml 決議器 ( https://github.com/BurntSushi/toml )
我正在嘗試解組以下 toml 檔案:
type (
fruitSpecs struct {
Id int `toml:"id"`
Name string `toml:"name"`
}
)
blob := `
[kiwi]
id = 1234581941
name = "kiwi"
`
o := &fruitSpecs{}
err := toml.Unmarshal([]byte(blob), o)
fmt.Println(o.Id)
好像當我使用表格時我[kiwi]似乎無法正確解組它。
如果我洗掉表名,我可以成功獲取 Id 欄位。
在嘗試成功構建將保存資料的整個結構時,我錯過了一些封裝?
我嘗試了以下方法來添加表名,但沒有任何積極的結果:
type (
fruitSpecs struct {
Id int `toml:"id"`
Name string `toml:"name"`
}
fruits struct {
fruit fruitSpecs
}
)
blob := `
[kiwi]
id = 1234581941
name = "kiwi"
`
o := &fruitSpecs{}
err := toml.Unmarshal([]byte(blob), o)
fmt.Println(o.Id)
但它錯誤:
o.Id undefined (type *fruitSpecs has no field or method Id)
uj5u.com熱心網友回復:
更新 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.Unmarshallto的變化,toml.Decode將結構生成到映射中fruitSpecs并在映射結構上進行互動。
這就是我解決這個問題的方法。
免費軟體。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/518004.html
標籤:去
下一篇:彈性搜索布爾查詢物件陣列應該子句
