在mgo结构中重置time.Time

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

Reset time.Time in mgo struct

问题

简化的结构体:

type User struct {
    ResetToken string    `bson:"resettoken,omitempty" json:"resettoken"`
    ResetSent  time.Time `bson:"resetsent,omitempty" json:"resetsent"`
}

现在在成功重置密码后,应该将ResetToken设置为"",将ResetSent设置为"uninitialized",即0或初始值或空值,你可以自己命名。

对于字符串,可以使用""和",omitempty"来实现,但对于time.Time类型该如何处理呢?

英文:

Simplified struct:

type User struct {
	ResetToken     string        `bson:"resettoken,omitempty" json:"resettoken"`
	ResetSent      time.Time     `bson:"resetsent,omitempty" json:"resetsent"`
}

Now on successful (password) reset it should set ResetToken = "" and
set ResetSent to "uninitialized" aka 0 or initial value or empty, you name it.

In the case of string it's done with "" and ",omitempty"
but how do I do with with time.Time?

答案1

得分: 3

时间零是time.Time{},你可以使用time.IsZero(t)来检查它是否为零。所以,类似这样的代码:

user.ResetSent = time.Time{}

如果你需要真正地使用omitempty,你可以使用*time.Time,这样如果为nil,它将保持为空。

更新:
Gustavo的评论是正确的,omitempty对于零值时间是按预期工作的,不需要使用指针。

英文:

The time zero is time.Time{}, and you can check that it's zero with time.IsZero(t). So, something like:

user.ResetSent = time.Time{}

If you need it to really omitempty, you could use a *time.Time, so it will leave it empty if nil.

Update:
Gustavo's comment is correct, omitempty works as intended for zero-valued time, without a pointer.

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

发表评论

匿名网友

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

确定