【问题标题】:Nullable time.Time可空时间.Time
【发布时间】:2014-07-03 23:20:57
【问题描述】:

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

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

由于指针可以是nil,我将RemindedAt 设为指针,但这需要代码知道At 变量之间的区别。有没有更优雅的方法来处理这个问题?

【问题讨论】:

  • “.”运算符同样适用于指针和非指针值。为什么代码需要“知道区别”?您的意思是在使用之前检查它是否为 nil 还是...?
  • 不,如果这是真的,那么我所拥有的就是有效的。我以为我必须处理取消引用。
  • @TobiLehman,在大多数情况下,Go 将 dereference pointers to structs,您的代码非常好。

标签: time go null


【解决方案1】:

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

来自 github 上的lib/pq

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】:

    我喜欢 lib/pq 中的 NullTime 示例。我以这种方式对其进行了调整,因此 NullTime 可以被视为 Time...

    type NullTime struct {
        time.Time
        Valid bool
    }
    

    【讨论】:

      【解决方案3】:

      可能还想检查 go-sql-driver 实现,这与上面推荐的基本相同。 https://godoc.org/github.com/go-sql-driver/mysql#NullTime

      【讨论】:

        【解决方案4】:

        mysql.NullTime 被贬低https://github.com/go-sql-driver/mysql/issues/960 从 Go1.13 开始,database/sql 将具有 NullTime 类型,应该使用它来代替 https://github.com/golang/go/issues/30305

        【讨论】:

          猜你喜欢
          • 2019-11-19
          • 2023-03-07
          • 1970-01-01
          • 2021-05-26
          • 2012-08-15
          • 1970-01-01
          • 1970-01-01
          • 2011-09-21
          • 2015-11-02
          相关资源
          最近更新 更多