go - 为什么用户定义的时间位置为零

标签 go

我正在使用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/

相关文章:

ssl - Golang 证书验证

go - 在字符串搜索中处理 Unicode

go - 如何使用乐高

process - 如何在golang中的exec.command中添加空格

go - 使用 Gocql 获取超时错误

amazon-web-services - AWS Golang SDK-如何将DeleteOnTermination放在EBS卷上?

testing - 改进测试。Go 的基准测试?

go - `size *= b - a` 是什么意思?

go - 写入特定的 bytes.Buffer 偏移量

go - 带有指针接收器的方法