Go - 在Struct中将NULL解析为time.Time

时间:2016-04-04 15:50:46

标签: go

我正在转换为具有time.Time类型的结构。

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

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

但是,有时我不想设置time.Time字段,你如何用go / mysql db驱动程序定义它?

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

基本上,我想要

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

我尝试在结构声明本身周围执行if并将LiveDate字段退出,但我收到错误controllers/apps.go:1068: undefined: app_history

1 个答案:

答案 0 :(得分: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,
  }
}