Nullable time.Time in golang

匿名 (未验证) 提交于 2019-12-03 02:45:02

问题:

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:

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 } 


回答2:

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:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!