我有一个打算用数据库记录填充的结构,其中一个日期时间列可以为空:
type Reminder struct {
Id int
CreatedAt time.Time
RemindedAt *time.Time
SenderId int
ReceiverId int
}
因为指针可以是nil
,所以我把Re MindAt
做成了一个指针,但这需要代码知道At
之间的区别> 变量。有没有更优雅的方法来处理这个问题?
最佳答案
您可以使用 pq.NullTime
,或者在 Go 1.13 中,您现在可以使用标准库的 sql.NullTime
输入。
来自 lib/pq在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
}
关于time - 可空时间.Time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24564619/