我想将我的 time.Time
字段编码为数字 Unix 时间,我不想为每个结构实现自定义 MarshalJSON 函数,因为我有很多很多结构。
所以,我尝试定义一个类型别名:
类型时间戳time.Time
并像这样在其上实现 MarshalJSON:
func (t Timestamp) MarshalJSON() ([]byte, error) {
return []byte(strconv.FormatInt(t.Unix(), 10)), nil
}
但这给了我一个 t.Unix undefined (type Timestamp has no field or method Unix)
,这对我来说没有意义。 Timestamp
不应该“继承”(我知道这可能是错误的术语)time.Time
的所有功能吗?
我也试过像这样使用类型断言:
strconv.FormatInt(t.(time.Time).Unix(), 10)
但这也失败了,提示类型断言无效:invalid type assertion: t.(time.Time) (non-interface type Timestamp on left)
最佳答案
您需要将您的类型转换回 time.Time
才能访问其方法。命名类型不会“继承”其基础类型的方法(为此,您需要 embedding )。
func (t Timestamp) MarshalJSON() ([]byte, error) {
return []byte(strconv.FormatInt(time.Time(t).Unix(), 10)), nil
}
此外,就个人喜好而言,我倾向于选择 fmt.Sprintf("%v", i)
而不是 strconv.FormatInt(i, 10)
甚至 strconv.Itoa(i)
。老实说,不确定哪个更快,但就个人而言,fmt
版本似乎更易于阅读。
关于go - 将时间字段编码为 Unix 时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41131041/