【问题标题】:Why do 2 time structs with the same date and time return false when compared with ==?为什么与 == 相比,具有相同日期和时间的 2 个时间结构返回 false?
【发布时间】:2016-08-05 12:35:05
【问题描述】:

我有一个使用time.Date() 创建的time.Time。然后我计算1970/1/1 00:00:00.000000000 和那个时间之间的纳秒数。

然后,我使用 time.Unix() 将纳秒转换回 time.Time。

但是,如果我使用 == 将重构时间与原始时间进行比较,它会返回 false。如果我减去这 2 次,得到的持续时间为 0。如果我使用 time.Equal() 比较这 2 次,它返回 true。

如果我使用time.Date() 创建另一个与第一次具有相同值的时间,则使用== 比较这个新时间和原始时间结果为真。

这是演示这一点的代码 (Golang Playground):

package main

import (
    "fmt"
    "time"
)

func main() {
    t1 := time.Date(2016, 4, 14, 1, 30, 30, 222000000, time.UTC)


    base := time.Date(1970, 1, 1, 0, 0, 0, 0, t1.Location())
    nsFrom1970 :=t1.Sub(base).Nanoseconds() // Calculate the number of nanoseconds from 1970/1/1 to t1

    t2 := time.Unix(0, nsFrom1970)

    fmt.Println(t1)
    fmt.Println(t2)
    fmt.Println(t1.Sub(t2)) // 0
    fmt.Println(t1 == t2) //false
    fmt.Println(t1.Equal(t2)) //true

    t3 := time.Date(2100, 2, 1, 21, 21, 21, 222000000, time.UTC)
    fmt.Println(t1 == t3) //true
}

为什么重构的时间与原来的时间相比返回false?

【问题讨论】:

    标签: go time struct date-comparison


    【解决方案1】:

    time.Time 是struct。当您尝试将它们与== 进行比较时,引用Spec: Comparison operator:

    如果结构值的所有字段都是可比较的,则结构值是可比较的。如果对应的非blank 字段相等,则两个结构值相等。

    所以t1 == t2 将比较 2 个Time 结构值的所有字段。 Time 结构不仅包含自基准时间以来的秒和纳秒,它还包含作为指针的位置:*Location,因此== 还将比较位置字段。比较指针:

    指针值是可比较的。如果两个指针值指向同一个变量,或者两者都具有值nil,则它们是相等的。指向不同 zero-size 变量的指针可能相等,也可能不相等。

    这就是为什么将时间与== 进行比较会得到false 的结果:即使地址不同,2 个位置也可能表示相同的位置,这就是你的情况。

    为了证明这一点:

    fmt.Println("Locations:", t1.Location(), t2.Location())
    fmt.Printf("Location pointers: %p %p\n", t1.Location(), t2.Location())
    fmt.Println("Locations equal:", t1.Location() == t2.Location())
    

    输出:

    Locations: UTC UTC
    Location pointers: 0x1e2100 0x1e6de0
    Locations equal: false
    

    这记录在time.Time:

    请注意,Go == 运算符不仅比较时间,还比较位置。因此,如果没有首先保证所有值都设置了相同的位置,则不应将时间值用作地图或数据库键,这可以通过使用 UTC 或本地方法来实现。

    如果t1 和t2 也包含相同的*Location 指针,即使与== 运算符相比,它们也将相等。这可以通过在它们上调用Time.UTC() 或Time.Local() 方法来确保,该方法返回一个time.Time 值,其中使用了相同的位置指针(*Location)。或者使用Time.In() 方法,该方法将设置指定的位置指针(在正确转换之后),例如:

    t2 = t2.In(t1.Location())
    fmt.Println("Locations:", t1.Location(), t2.Location())
    fmt.Printf("Location pointers: %p %p\n", t1.Location(), t2.Location())
    fmt.Println("Locations equal:", t1.Location() == t2.Location())
    fmt.Println(t1 == t2)     // Now true
    fmt.Println(t1.Equal(t2)) // Still true
    

    输出:

    Locations: UTC UTC
    Location pointers: 0x1e2100 0x1e2100
    Locations equal: true
    true
    true
    

    在Go Playground 上试用。

    【讨论】:

      猜你喜欢
      • 2013-04-09
      • 1970-01-01
      • 2017-06-10
      • 2015-04-07
      • 2020-11-29
      • 2019-03-02
      • 2021-04-14
      • 2019-12-06
      • 1970-01-01
      相关资源
      最近更新 更多