空时间 [英] Nullable time.Time
本文介绍了空时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个要用数据库记录填充的结构,其中datetime列之一可以为空:
I have a struct that I intend to populate with a database record, one of the datetime columns is nullable:
type Reminder struct {
Id int
CreatedAt time.Time
RemindedAt *time.Time
SenderId int
ReceiverId int
}
由于指针可以是nil
,所以我将RemindedAt
设置为指针,但这将需要代码知道At
变量之间的区别.有没有更优雅的方式来解决这个问题?
Since pointers can be nil
, I've made RemindedAt
a pointer, but this will require the code to know the difference between the At
variables. Is there a more elegant way to handle this?
推荐答案
您可以使用pq.NullTime
,或者在Go 1.13中,现在可以使用标准库的
You can use pq.NullTime
, or with Go 1.13, you can now use the standard library's sql.NullTime
type.
在github上的 lib/pq 上:
From lib/pq on 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
}
这篇关于空时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文