doulan0297 2016-12-13 21:41
浏览 84
已采纳

编组时间字段为Unix时间

I want to encode my time.Time fields as numeric Unix time and I would prefer not to implement custom MarshalJSON functions for each and every struct, since I have lots and lots of structs.

So, I tried defining a type alias as such:

type Timestamp time.Time

And implementing MarshalJSON on it like so:

func (t Timestamp) MarshalJSON() ([]byte, error) {
    return []byte(strconv.FormatInt(t.Unix(), 10)), nil
}

But that gives me a t.Unix undefined (type Timestamp has no field or method Unix), which doesn't make sense to me. Shouldn't Timestamp 'inherit' (I know that's probably the wrong term) all functions of time.Time?

I also tried using a type assertion like so:

strconv.FormatInt(t.(time.Time).Unix(), 10)

But that also fails, complaining about an invalid type assertion: invalid type assertion: t.(time.Time) (non-interface type Timestamp on left)

  • 写回答

1条回答 默认 最新

  • doujuxin7392 2016-12-13 21:51
    关注

    You need to convert your type back to a time.Time to have access to its methods. Named types do not "inherit" the methods of their underlying types (to do that, you need embedding).

    func (t Timestamp) MarshalJSON() ([]byte, error) {
        return []byte(strconv.FormatInt(time.Time(t).Unix(), 10)), nil
    }
    

    Also, just as a matter of personal preference, I tend to preferred fmt.Sprintf("%v", i) over strconv.FormatInt(i, 10) or even strconv.Itoa(i). Honestly not sure which is faster, but the fmt version seems easier to read, personally.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算