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