可空的时间.时间 [英] Nullable time.Time

查看:16
本文介绍了可空的时间.时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要填充数据库记录的结构,其中一个日期时间列可以为空:

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
}

因为指针可以是nil,所以我把RemittedAt 变成了一个指针,但这需要代码知道At 之间的区别> 变量.有没有更优雅的方法来处理这个问题?

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?

推荐答案

您可以使用 pq.NullTime,或者在 Go 1.13 中,您现在可以使用标准库的 sql.NullTime 类型.

You can use pq.NullTime, or with Go 1.13, you can now use the standard library's sql.NullTime type.

来自 github 上的 lib/pq:

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
}

这篇关于可空的时间.时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆