go - 将时间字段编码为 Unix 时间

标签 go

我想将我的 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/

相关文章:

html - 如何使用 GO (golang) 在 HTML 中嵌入 SQLX 结果

go - 从golang中的优先级队列中删除元素

pointers - 遍历一片结构并更新值

go - 如何在无错误的情况下按键编写互斥锁?

python - 如何使用 exec 命令将字节数据从 golang 发送到 python?

json - 在 golang 版本之间使用自定义解码器解析 json 的差异

go - 使用 go 创建新的 ldap 条目

go - 为什么 'Open connection failed:sql: unknown driver "mssql“(忘记导入?)”会在 go build 中第一次发生?

mongodb - 使用 Go 在 MongoDB 中指定查询

go - 获取 "implicit assignment of unexported field"