3 回答

TA貢獻1805條經驗 獲得超10個贊
試試這個,如果那適合你更好
package main
import (
"fmt"
)
func main() {
fmt.Printf("%#v\n",deviceSchemaJson)
}
var deviceSchemaJson = value{
"additionalProperties": false,
"properties": value{
"application": value{
"type": "string",
},
"hostname": value{
"type": "string",
},
"ipaddress": value{
"oneOf": []valuestring{{"format": "ipv4"}, {"format": "ipv6"}},
"type": "string",
},
"kernel_version": valuestring{
"type": "string",
},
},
"type": "object",
}
type value map[string]interface{}
type valuestring map[string]string
https://play.golang.org/p/6Kq5pvXYvNm

TA貢獻1793條經驗 獲得超6個贊
如何避免每次都定義?map[string]string
通過定義表示數據結構的類型。
type DeviceSchema struct {
AdditionalProperties bool
Properties Properties
Type string
}
type Properties struct {
Application string
Hostname string
IpAddress []map[string]string
KernelVersion string
}
func main() {
deviceSchemaData := DeviceSchema{
AdditionalProperties: false,
Properties: Properties{
IpAddress: []map[string]string{{"format": "ipv4"},{"format": "ipv6"}},
},
Type: "object",
}
fmt.Println(deviceSchemaData)
}
https://play.golang.org/p/iHfoft1zyAn

TA貢獻1827條經驗 獲得超4個贊
簡化定義的一種方法是:
func stringMap(s...string) map[string]string {
ret:=map[string]string{}
for i:=0; i<len(s);i+=2 {
ret[s[i]]=s[i+1]
}
return ret
}
var deviceSchemaJson = map[string]interface{}{
"additionalProperties": false,
"properties": map[string]interface{}{
"application": stringMap("type","string"),
"hostname": stringMap("type","string"),
"ipaddress": map[string]interface{}{
"oneOf": []map[string]string{stringMap("format","ipv4"),stringMap("format","ipv6")},
"type": "string",
},
"kernel_version": stringMap("type","string"),
},
"type": "object",
}
- 3 回答
- 0 關注
- 110 瀏覽
添加回答
舉報