我正在使用go 1.13,我有一个用户定义的类型time.Time
类型,当使用给定位置的UTC
创建该值时,loc
属性仍然是nil
(设置为nil loc
会导致某些时间函数出现 panic ,所以这是不能接受的)。游乐场here。
type CustomTime time.Time
func main() {
t := CustomTime(time.Date(2020, time.July, 23, 1, 0, 0, 0, time.UTC))
fmt.Printf("%+v",t) // prints {wall:0 ext:63731062800 loc:<nil>}
}
仅供引用:背景信息,我正在使用此自定义时间为我的数据库处理程序实现Scan()
,当我比较上面定义的自定义时间值(具有nil
位置与db中的值(非nil
位置)时,我的测试是由于比较失败而导致失败,请多多指教。
最佳答案
如果您查看文档,则time.Time属于类型
type Time struct {
//...
wall uint64
ext int64
// loc specifies the Location that should be used to
// determine the minute, hour, month, day, and year
// that correspond to this Time.
// The nil location means UTC.
// All UTC times are represented with loc==nil, never loc==&utcLoc.
loc *Location
}
nil loc
实际上表示UTC。您可以通过打印相等性来验证相同性fmt.Println(time.UTC == time.Time(t).Location())
// Output: true
当您打印t
时会看到一个nil,因为您实际上是在打印struct Time
而不使用它的默认Stringer
,因为您已经用“自定义类型”即CustomTime
包装了它。因此,loc
字段将为nil。fmt.Printf("%+v", time.Time(t))
// This will print UTC for the location.
如果您想在各处使用CustomTime
,则无需创建类型别名,而可以将time.Time
嵌入结构中,以便CustomTime
的行为类似于time.Time
type CustomTime struct {
time.Time
}
func main() {
t := CustomTime{time.Date(2020, time.July, 23, 1, 0, 0, 0, time.UTC)}
fmt.Printf("%+v", t) // Prints: 2020-07-23 01:00:00 +0000 UTC
}
关于go - 为什么用户定义的时间位置为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63067760/