Go – Parse NULL to time.Time in Struct

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

Go - Parse NULL to time.Time in Struct

问题

我正在翻译以下内容:

我正在将一个具有time.Time类型的结构体进行转换。

  1. t2 := time.Now()
  2. format := "2006-01-02 15:04:05"
  3. theTime, _ := time.Parse(format, t2.Format(format))

然而,有时我不想设置time.Time字段,你如何在go/mysql数据库驱动中定义这个?

  1. app_history := &models.AppsHistoryInsert{
  2. AppId: response.SetAppData[0].Id,
  3. LiveDate: &theTime,
  4. }

基本上,我想要:

  1. if(x == true) {
  2. 包含时间
  3. }
  4. else {
  5. 不包含时间
  6. }

我尝试在结构体声明周围使用if,并将LiveDate字段省略,但是我得到了controllers/apps.go:1068: undefined: app_history的错误。

英文:

I am casting to a struct which has a time.Time type in.

  1. t2 := time.Now()
  2. format := "2006-01-02 15:04:05"
  3. theTime, _ := time.Parse(format, t2.Format(format))

However, sometimes I don't want to set the time.Time field, how do you define this with the go/mysql db driver?

  1. app_history := &models.AppsHistoryInsert{
  2. AppId: response.SetAppData[0].Id,
  3. LiveDate: &theTime,
  4. }

Basically, I want

  1. if(x == true) {
  2. include time
  3. }
  4. else {
  5. don't include time.
  6. }

I tried doing an if around the struct declaration itself and leaving the LiveDate field out but I got the error of controllers/apps.go:1068: undefined: app_history

答案1

得分: 3

你需要在if语句之外定义app_history变量,并在每个分支中对其进行赋值。

像这样:

  1. var app_history &models.AppsHistoryInsert{}
  2. if x {
  3. app_history = &models.AppsHistoryInsert{
  4. AppId: response.SetAppData[0].Id,
  5. LiveDate: &theTime,
  6. }
  7. } else {
  8. app_history = &models.AppsHistoryInsert{
  9. AppId: response.SetAppData[0].Id,
  10. }
  11. }
英文:

you need to define the app_history variable outside the if statement and then assign to it in each of the branches

like so

  1. var app_history &models.AppsHistoryInsert{}
  2. if x {
  3. app_history = &models.AppsHistoryInsert{
  4. AppId: response.SetAppData[0].Id,
  5. LiveDate: &theTime,
  6. }
  7. }else {
  8. app_history = &models.AppsHistoryInsert{
  9. AppId: response.SetAppData[0].Id,
  10. }
  11. }

huangapple
  • 本文由 发表于 2016年4月4日 23:50:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/36407297.html
匿名

发表评论

匿名网友

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

确定