可空的 time.Time

huangapple go评论74阅读模式
英文:

Nullable time.Time

问题

我有一个结构体,我打算用数据库记录填充它,其中一个datetime列是可空的:

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

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

英文:

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

得分: 83

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

在github上的lib/pq中:

type NullTime struct {
    Time  time.Time
    Valid bool // 如果Time不为NULL,则Valid为true
}

// Scan 实现了Scanner接口。
func (nt *NullTime) Scan(value interface{}) error {
    nt.Time, nt.Valid = value.(time.Time)
    return nil
}

// Value 实现了driver Valuer接口。
func (nt NullTime) Value() (driver.Value, error) {
    if !nt.Valid {
        return nil, nil
    }
    return nt.Time, nil
}
英文:

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
}

答案2

得分: 7

我喜欢lib/pq中的NullTime示例。我对它进行了一些调整,使得NullTime可以像Time一样处理。

type NullTime struct {
    time.Time
    Valid bool
}
英文:

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

得分: 3

你可能还想检查一下go-sql-driver的实现,它基本上与上面推荐的是一样的。https://godoc.org/github.com/go-sql-driver/mysql#NullTime

英文:

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

答案4

得分: 3

mysql.NullTime已被弃用https://github.com/go-sql-driver/mysql/issues/960
从Go1.13开始,database/sql将使用NullTime类型,应该使用该类型
https://github.com/golang/go/issues/30305

英文:

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

huangapple
  • 本文由 发表于 2014年7月4日 07:20:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/24564619.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定