首页 > 解决方案 > 定义此嵌套映射时如何避免重复

问题描述

在我的一个 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每次都定义?

标签: dictionarygostruct

解决方案


如果这更适合你,试试这个

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


推荐阅读