登录
首页 >  Golang >  Go问答

避免重复的方法:定义嵌套映射

来源:stackoverflow

时间:2024-03-21 14:18:28 365浏览 收藏

在定义 JSON 模式时,重复定义 map[string]string 可能会很麻烦。为了避免这种情况,可以创建一个自定义类型,该类型包含一个嵌套映射。自定义类型定义了一个值和一个值字符串,分别对应于映射的键和值。使用自定义类型,可以更简洁地定义 JSON 模式,避免重复定义 map[string]string。

问题内容

在我的一个 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


正确答案


如果更适合您,请尝试一下

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

本篇关于《避免重复的方法:定义嵌套映射》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>