dpz7935 2019-09-11 15:12
浏览 82

对于可为空的结构字段,最好使用nil或Null * [关闭]

Here I saw a question about nullable fields in struct. From Go 1.13 you can use sql.NullTime (earlier declared in pg and mysql). From now we can use these two options to declare the ResolvedAt nullable time field:

A. ResolvedAt as NullTime:

type Event struct {
    Id         int   
    Resolved   bool
    CreatedAt  time.Time
    ResolvedAt sql.NullTime        
}

B. ResolvedAt as pointer:

type Event struct {
    Id         int 
    Resolved   bool
    CreatedAt  time.Time
    ResolvedAt *time.Time
}

For Scan method there is no difference:

rows, err := db.Query("SELECT * FROM Event")

for rows.Next() {
    e:= new(Event)
    err := rows.Scan(&e.Id, &e.CreatedAt, &e.ResolvedAt)
}  

But when testing for Null there is a difference:

// A. 
e.Resolved = (e.ResolvedAt != nil)  
// B.  
e.Resolved = (e.ResolvedAt.Valid)

In which case is SHOULD to use Null... type rather then pointer?

  • 写回答

2条回答 默认 最新

  • douyanqu9722 2019-09-11 15:28
    关注

    I would recommend using the sql.Null types, because it is easier to understand what is going on when reading the code.

    If you are using nil pointers it is unclear what you are trying to accomplish by making those fields pointers.

    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序