duanqinqiao4844 2015-11-01 01:46
浏览 690
已采纳

在Golang中使用sql.NullFloat64与* float64?

I'm using gorm to define my db table schema. Noticed that gorm itself uses time.Time for created_at and *time.Time for deleted_at. I'm assuming this is because deleted_at has cases of being NULL.

I also noticed that for many Golang ORMs they use sql.NullFloat64 for storing db values that could be a float64 or NULL. Why not just use *float64 instead of sql.NullFloat64? What's the difference?

type Geo struct {
    latitude *float64
    longitude sql.NullFloat64
}
// What is the difference between latitude and longitude in this case?
  • 写回答

1条回答 默认 最新

  • dongrunying7537 2015-11-01 06:31
    关注

    From Russ Cox (biggest Go's contributor according to Github) : https://groups.google.com/forum/#!topic/golang-nuts/vOTFu2SMNeA

    There's no effective difference. We thought people might want to use NullString because it is so common and perhaps expresses the intent more clearly than *string. But either will work.

    I'm thinking though that using a pointer might give the GC one more thing to track. It probably depends on the usage.

    On some very simple code, using -gcflags=-m to build, the escape analysis does say that new(float64) escapes to heap (here is the dummy code I used: https://play.golang.org/p/K4sQaXyQKG).

    Also, when debugging, printing a struct containing a sql.NullSomething ({value:{Float64:1 Valid:true}}) looks better than a struct containing a pointer ({value:0xc82000a420}).

    So I'd recommend the usage of the sql.Null* structs.

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

报告相同问题?

悬赏问题

  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签)
  • ¥50 sft下载大文阻塞卡死
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失
  • ¥15 springboot+vue 集成keycloak sso到阿里云
  • ¥15 win7系统进入桌面过一秒后突然黑屏
  • ¥30 backtrader对于期货交易的现金和资产计算的问题
  • ¥15 求C# .net4.8小报表工具
  • ¥15 安装虚拟机时出现问题