避免重复的方法:定义嵌套映射
时间:2024-03-21
浏览: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学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
12.01
12.01
12.01
热门专题
