Time 可为空的时间
我有一个要用数据库记录填充的结构,其中一个datetime列可为空:Time 可为空的时间,time,go,null,Time,Go,Null,我有一个要用数据库记录填充的结构,其中一个datetime列可为空: type Reminder struct { Id int CreatedAt time.Time RemindedAt *time.Time SenderId int ReceiverId int } 由于指针可以是nil,因此我将remidedat设置为指针,但这需要代码知道At变量之间的差异。是否有更优雅的方法来处理此问题?您可以使用pq.NullTime,
type Reminder struct {
Id int
CreatedAt time.Time
RemindedAt *time.Time
SenderId int
ReceiverId int
}
由于指针可以是
nil
,因此我将remidedat
设置为指针,但这需要代码知道At
变量之间的差异。是否有更优雅的方法来处理此问题?您可以使用pq.NullTime
,或者使用Go 1.13,您现在可以使用标准库的类型
从github:
type NullTime struct {
Time time.Time
Valid bool // Valid is true if Time is not NULL
}
// Scan implements the Scanner interface.
func (nt *NullTime) Scan(value interface{}) error {
nt.Time, nt.Valid = value.(time.Time)
return nil
}
// Value implements the driver Valuer interface.
func (nt NullTime) Value() (driver.Value, error) {
if !nt.Valid {
return nil, nil
}
return nt.Time, nil
}
我喜欢lib/pq中的
NullTime
示例。我以这种方式对它进行了调整,因此NullTime
可以像Time
一样处理
type NullTime struct {
time.Time
Valid bool
}
可能还需要检查GoSQL驱动程序实现,这与上面推荐的基本相同 mysql.NullTime已去除润滑脂 从Go1.13开始,database/sql将有一个NullTime类型,应该改用它
“.”运算符对指针和非指针值同样有效。为什么代码需要“了解差异”?你的意思是在使用它之前检查它是否为零还是…?不,如果是真的,那么我所拥有的工作。我以为我必须处理去引用。@TobiLehman,在大多数情况下,Go will,您的代码非常好。