Nullable time.Time

后端 未结 4 1845
醉酒成梦
醉酒成梦 2020-12-08 00:26

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
    Crea         


        
相关标签:
4条回答
  • 2020-12-08 00:55

    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

    0 讨论(0)
  • 2020-12-08 01:15

    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
    }
    
    0 讨论(0)
  • 2020-12-08 01:16

    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
    }
    
    0 讨论(0)
  • 2020-12-08 01:20

    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

    0 讨论(0)
提交回复
热议问题