可空时间。golang时间 [英] Nullable time.Time in golang
本文介绍了可空时间。golang时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个结构,我打算填充一个数据库记录,其中一个datetime列可以为空:
type提醒struct {
Id int
CreatedAt time.Time
RemindedAt * time.Time
SenderId int
ReceiverId int
}
$因为指针可以是 nil
,所以我使
> RemindedAt 一个指针,但是这需要代码知道 At
变量之间的区别。有没有更好的方法来处理这个问题? c $ c>。
From lib / pq :
类型NullTime结构{
Time time.Time
有效bool //如果时间不为NULL,则有效为真
}
//扫描实现扫描器界面。
func(nt * NullTime)Scan(value interface {})错误{
nt.Time,nt.Valid = value。(time.Time)
return nil
}
// Value实现驱动器Valuer接口。
func(nt NullTime)Value()(driver.Value,error){
if!nt.Valid {
return nil,nil
}
return nt。时间,无
}
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
}
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?
解决方案
You can use pq.NullTime
.
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
}
这篇关于可空时间。golang时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文