猿问

定义此嵌套映射时如何避免重复

在我的一个json架构中,我有一个这样的地图


var deviceSchemaJson = map[string]interface{}{

    "additionalProperties": false,

    "properties": map[string]interface{}{

        "application": map[string]string{

            "type": "string",

        },

        "hostname": map[string]string{

            "type": "string",

        },

        "ipaddress": map[string]interface{}{

            "oneOf": []map[string]string{{"format": "ipv4"},{"format": "ipv6"}},

            "type": "string",

        },

        "kernel_version": map[string]string{

            "type": "string",

        },

    },

    "type": "object",

}

如何避免每次都定义?map[string]string


汪汪一只猫
浏览 90回答 3
3回答

holdtom

试试这个,如果那适合你更好package mainimport (    "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]stringhttps://play.golang.org/p/6Kq5pvXYvNm

摇曳的蔷薇

如何避免每次都定义?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

GCT1015

简化定义的一种方法是:func stringMap(s...string) map[string]string {&nbsp; ret:=map[string]string{}&nbsp; for i:=0; i<len(s);i+=2 {&nbsp; &nbsp; &nbsp;ret[s[i]]=s[i+1]&nbsp; }&nbsp; return ret}var deviceSchemaJson = map[string]interface{}{&nbsp; &nbsp; "additionalProperties": false,&nbsp; &nbsp; "properties": map[string]interface{}{&nbsp; &nbsp; &nbsp; &nbsp; "application": stringMap("type","string"),&nbsp; &nbsp; &nbsp; &nbsp; "hostname": stringMap("type","string"),&nbsp; &nbsp; &nbsp; &nbsp; "ipaddress": map[string]interface{}{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "oneOf": []map[string]string{stringMap("format","ipv4"),stringMap("format","ipv6")},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "type": "string",&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; "kernel_version": stringMap("type","string"),&nbsp; &nbsp; },&nbsp; &nbsp; "type": "object",}
随时随地看视频慕课网APP

相关分类

Go
我要回答