doufengsui7449 2019-06-11 11:52
浏览 550

如何在DataStore中存储* time.Time类型的struct字段的当前时间? [重复]

This question already has an answer here:

According to my requirements, I created one struct as -

type MyRule struct {
   CreatedAt    time.Time  `json:"createdAt" datastore:"createdAt,noindex"`
   UpdatedAt    *time.Time  `json:"updatedAt" datastore:"updatedAt,noindex"`
}

for createdAt field, I am able to store current time as-

MyRule.CreatedAt = time.Now()

However, the same thing does not work to store current time in updatedAt field of MyRule struct as it's type is *time.Time and not time.Time. Here, I can't change field type of updatedAt because *time.Time allows me to accept nil as updatedAt value when I create any rule.

If I try to do this as-

 MyRule.UpdatedAt = time.Now()

It gives me below error-

 cannot use time.Now()(type time.Time) as type *time.Time in assignment

How can I store current time value in updatedAt field of type *time.Time and not time.Time

</div>
  • 写回答

1条回答 默认 最新

  • dongxi7609 2019-06-11 12:39
    关注

    Note: one cannot get the address of a return value, so something like this will NOT work:

    MyRule.UpdatedAt = &time.Now() // compile fail
    

    To get the address of a value, it must be in an addressable item. So assign the value to a variable, like so:

    t := time.Now()
    MyRule.UpdatedAt = &t
    
    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题