Go – Parse NULL to time.Time in Struct

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

Go - Parse NULL to time.Time in Struct

问题

我正在翻译以下内容:

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

t2 := time.Now()
format := "2006-01-02 15:04:05"

theTime, _ := time.Parse(format, t2.Format(format))

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

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

基本上,我想要:

if(x == true) { 
    包含时间 
}
else {
    不包含时间 
}

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

英文:

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

t2 := time.Now()
format := "2006-01-02 15:04:05"

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?

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

Basically, I want

if(x == true) { 
    include time 
}
else {
    don't include time. 
}

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变量,并在每个分支中对其进行赋值。

像这样:

var app_history &models.AppsHistoryInsert{}

if x {
  app_history = &models.AppsHistoryInsert{
    AppId:          response.SetAppData[0].Id,
    LiveDate:       &theTime,
  }
} else {
  app_history = &models.AppsHistoryInsert{
    AppId:          response.SetAppData[0].Id,
  }
}
英文:

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

like so

var app_history &models.AppsHistoryInsert{}

if x {
  app_history = &models.AppsHistoryInsert{
    AppId:          response.SetAppData[0].Id,
    LiveDate:       &theTime,
  }
}else {
  app_history = &models.AppsHistoryInsert{
    AppId:          response.SetAppData[0].Id,
  }
}

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:

确定