dosgy00204 2014-02-27 16:12
浏览 14
已采纳

time.Time:指针或值

The Go docs say (emphasis added):

Programs using times should typically store and pass them as values, not pointers. That is, time variables and struct fields should be of type time.Time, not *time.Time. A Time value can be used by multiple goroutines simultaneously.

Is the last sentence (about using a Time value in multiple goroutines simultaneously) the only reason that they should "typically" be stored and passed as a value, rather than a pointer? Is this common to other structs as well? I tried looking for any logic that specifically enables this in the time.Time declaration and methods, but didn't notice anything special there.

Update: I often have to serve JSON representations of my structs, and I'd rather omit empty/uninitialized times. The json:",omitempty" tag doesn't work with time.Time values, which appears to be the expected behavior, but the best workaround seems to be to use a pointer, which goes against the advice in the docs quoted above.

  • 写回答

1条回答 默认 最新

  • dou47278 2014-02-27 16:13
    关注

    It's common for many kind of simple values.

    In Go, when some value isn't bigger than one or two words, it's common to simply use it as a value instead of using a pointer. Simply because there's no reason to use a pointer if the object is small and you don't pass it to be changed.

    You might have to unlearn the practice of languages where everything structured couldn't be handled as values. It's probably natural for you to use integers or floating point numbers as values, not pointers. Why not do the same for times ?

    Regarding your precise problem with JSON and assuming you don't want to write a specific Marshaller just for this, there's no problem in using a *time.Time. In fact this issue was already mentioned in the golang-nuts list.

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

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 ARIMA模型时间序列预测用pathon解决
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)