英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论