1、定义2个变量,1个类型是 time.Time ,1个类型是 *time.Time
var (
t1 = time.Now()
t2 *time.Time
)
2、有个需求,写一个函数,根据t1和t2的值进行 分别输出 不同内容,t1输出格式化后的时间,t2输出nil空指针
t1变量输出格式化时间
t2变量输出空白
思路:由于2个变量是不同类型,那么函数的参数就只能是interface{},返回值也只能是interface{}。
func Do(t interface{}) interface{} {}
函数内部可以用 switch case default 进行分别判断
switch reflect.TypeOf(t).String() {
case "time.Time":
return t.(time.Time).Format("2006-01-02 15:04:05")
case "*time.Time":
return t.(*time.Time)
default:
return ""
}
首先判断类型,当类型是”time.Time”,就通过通过 类型断言 t.(time.Time)进行转化时间,然后通过Format(“2006-01-02 15:04:05”)进行格式化。
当类型是”*time.Time”时,就通过类型断言输出指针类型。
其他情况输出为空字符串
在Gin Gorm迁移数据库中,当 deleted_at为空或不确定 时,而created_at和updated_at存在值,为了方便输出格式化时间,如果不经判断直接输出,那么当deleted_at为空时,就会出现错误,从而导致无法正常显示。

而直接输出,又结果又不太友好,那么就可以写一个自定义模板函数,进行判断输出,比默认的format效果要好很多。

模板自定义函数

为Gin增加模板自定义函数

在模板中使用自定义函数

执行结果
可能这并不是最完美的解决方案,你有什么好的方法,欢迎交流学习。
