英文:
Nullable time.Time
问题
我有一个结构体,我打算用数据库记录填充它,其中一个datetime列是可空的:
type Reminder struct {
Id int
CreatedAt time.Time
RemindedAt *time.Time
SenderId int
ReceiverId int
}
由于指针可以为nil
,我将RemindedAt
设置为指针,但这将需要代码知道At
变量之间的区别。有没有更优雅的方法来处理这个问题?
英文:
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?
答案1
得分: 83
你可以使用pq.NullTime
,或者在Go 1.13中,你现在可以使用标准库的sql.NullTime
类型。
在github上的lib/pq中:
type NullTime struct {
Time time.Time
Valid bool // 如果Time不为NULL,则Valid为true
}
// Scan 实现了Scanner接口。
func (nt *NullTime) Scan(value interface{}) error {
nt.Time, nt.Valid = value.(time.Time)
return nil
}
// Value 实现了driver Valuer接口。
func (nt NullTime) Value() (driver.Value, error) {
if !nt.Valid {
return nil, nil
}
return nt.Time, nil
}
英文:
You can use pq.NullTime
, or with Go 1.13, you can now use the standard library's sql.NullTime
type.
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
}
答案2
得分: 7
我喜欢lib/pq中的NullTime
示例。我对它进行了一些调整,使得NullTime
可以像Time
一样处理。
type NullTime struct {
time.Time
Valid bool
}
英文:
I like the NullTime
example from lib/pq. I tweaked it this way so the NullTime
can be treated like a Time
...
type NullTime struct {
time.Time
Valid bool
}
答案3
得分: 3
你可能还想检查一下go-sql-driver的实现,它基本上与上面推荐的是一样的。https://godoc.org/github.com/go-sql-driver/mysql#NullTime
英文:
Might also want to check the go-sql-driver implementation, which is basically the same thing as recommended above. https://godoc.org/github.com/go-sql-driver/mysql#NullTime
答案4
得分: 3
mysql.NullTime已被弃用https://github.com/go-sql-driver/mysql/issues/960
从Go1.13开始,database/sql将使用NullTime类型,应该使用该类型
https://github.com/golang/go/issues/30305
英文:
mysql.NullTime is depricated https://github.com/go-sql-driver/mysql/issues/960
database/sql will have a NullTime type from Go1.13 onward, which should be used instead
https://github.com/golang/go/issues/30305
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论