time - 可空时间.Time

标签 time go null

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

type Reminder struct {
    Id         int
    CreatedAt  time.Time
    RemindedAt *time.Time
    SenderId   int
    ReceiverId int
}

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

最佳答案

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

来自 lib/pq在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
}

关于time - 可空时间.Time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24564619/

相关文章:

linux - 如何将时间戳从十六进制格式转换为 EPOCH 时间戳?

java - 该算法的时间复杂度是多少?

java - 空对象 - 实例化或单例的东西?

java - NULL 对象的 StringBuffer 行为

c - 如何为数组的任何未填充部分分配空字符,然后将其写入文件?

swift - 在 Swift 3 中获取时差

python - 如何检查时间值?

json - 将 JSON 对象中的两个值连接到 Go 中的 map[string]bool

go - 如何在查询中使用Firestore DocumentID __name__

linux - 避免解析 Xrandr 输出