根据https://play.golang.org/p/7RPExbwOEU,它们都打印相同并具有相同的长度和容量.初始化切片的三种方法之间有区别吗?有首选方式吗?我发现自己同时使用make([]int, 0),并[]int{}具有相同的频率.
我有一个类型MonthYear定义如下
type MonthYear time.Time
func (my *MonthYear) MarshalJSON() ([]byte, error) {
t := time.Time(*my)
return json.Marshal(&struct {
Month int `json:"month"`
Year int `json:"year"`
}{
Month: int(t.Month()) - 1,
Year: t.Year(),
})
}
Run Code Online (Sandbox Code Playgroud)
我将它包含在很多不同的结构中,例如
type Event struct {
Name string `json:"name"`
Date MonthYear
}
type Item struct {
Category string `json:"category"`
Date MonthYear
}
Run Code Online (Sandbox Code Playgroud)
如何内联MonthYear类型以使生成的 JSON 不包含任何嵌入对象?
我希望结果看起来像这样{ "name": "party", "month": 2, "year": 2017 },而{ "category": "art", "month": 3, "year": 2016 }不必为每个结构编写 MarshalJSON。