小编yef*_*fim的帖子

make([] int,0),[] int {}和*new([] int)之间有什么区别?

根据https://play.golang.org/p/7RPExbwOEU,它们都打印相同并具有相同的长度和容量.初始化切片的三种方法之间有区别吗?有首选方式吗?我发现自己同时使用make([]int, 0),并[]int{}具有相同的频率.

go slice

3
推荐指数
1
解决办法
622
查看次数

编组 JSON 时如何内联字段?

我有一个类型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。

json marshalling go

3
推荐指数
1
解决办法
2万
查看次数

标签 统计

go ×2

json ×1

marshalling ×1

slice ×1