Go - 将 NULL 解析为 time.Time in Struct

标签 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 driver怎么定义呢?

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 的错误:未定义:app_history

最佳答案

你需要在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,
  }
}

关于Go - 将 NULL 解析为 time.Time in Struct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36407297/

相关文章:

mysql - Golang 在 Struct 属性中使用小写首字母

go - Go Imaginary Literals 的最佳用途是什么?

google-app-engine - gorilla mux 子域

戈朗 : How to implement the transfer method/function

go - 如何在 Golang 中对两个字符串数组进行异或?

go - 如何从现有结构修改对象和结构?

go - Redis golang 客户端定期丢弃错误的 PubSub 连接 (EOF)

Golang在接口(interface)指针上调用方法

apache - debian上的golang/apache/cgi-apache重定向停止工作

go - 通过 html/template 删除传递参数周围的空格