dtz30833 2015-01-16 17:14
浏览 28
已采纳

将time.Date分配给* time.Time指针以测试JSON反序列化

I have a struct, where one of the fields was declared as String, but it was intended to store a Time. Therefore I changed it to *time.Time (see the commit), note the use of a pointer to bypass the issue where ",omitempty" doesn't really omit the value in case of an blank date.

So far so good. The problem is that now I'm trying to write a code that tests the correct deserialization of the JSON string, but I can't compare the result with

want := Record{Id: 1539, UpdatedAt: time.Date(2014, 01, 15, 22, 03, 04, 0, time.UTC)}

because UpdatedAt is expected to be a pointer *time.Time, whereas time.Date returns a time.Time.

I can't use

want := Record{Id: 1539, UpdatedAt: &time.Date(2014, 01, 15, 22, 03, 04, 0, time.UTC)}

because it is indeed rejected (it expects a pointer, I try to assign a struct)

cannot take the address of time.Date(2014, 1, 15, 22, 3, 3, 0, time.UTC)

Here's my question. Is there a way to create a Record with a time.Date on the fly (hence without assigning the time.Date to a variable and then get the pointer) and/or a workaround for the issue that guarantees I can have a proper nil value assigned when the object is serialized/deserialized and the date is blank?

  • 写回答

2条回答 默认 最新

  • dongqi4085 2015-01-16 18:43
    关注

    You can't take the address of a function return value because you can only take the address of something that can be assigned to.

    Think of it this way: if you store the result in variable, you can then take the address of that variable, but if you don't, then there's nothing you can take the address from.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题