英文:
reflect.DeepEqual not working on timestamp comparison
问题
我正在尝试编写一个测试用例来比较 Golang 中的时间戳。问题是 reflect.DeepEqual 无法检查两个时间戳是否相等:
package main
import (
"fmt"
"reflect"
"time"
)
func main() {
timestamp1, _ := time.Parse(time.RFC3339, "2021-08-03T07:26:34Z")
timestamp2 := time.Unix(0, int64(time.Millisecond)*timestamp1.UnixMilli())
fmt.Printf("两个时间戳是否相等:%v", reflect.DeepEqual(timestamp1, timestamp2))
}
有人能告诉我在这个比较中可能出了什么问题吗?
英文:
I am trying to write a test case to compare timestamps in golang. The problem is that reflect.DeepEqual is not able to check whether 2 timestamps are equal:
package main
import (
"fmt"
"reflect"
"time"
)
func main() {
timestamp1, _ := time.Parse(time.RFC3339, "2021-08-03T07:26:34Z")
timestamp2 := time.Unix(0, int64(time.Millisecond)*timestamp1.UnixMilli())
fmt.Printf("are both timestamps equal: %v", reflect.DeepEqual(timestamp1, timestamp2))
}
Could anyone tell me what might be going wrong in this comparison?
答案1
得分: 3
reflect.DeepEqual
是用来判断两个对象是否深度相等的,它并不关心"timestamps"(时间戳)。多个表示相同时间点的"timestamps"可能会有不同的time.Time
表示。
如果你想比较一个time.Time
表示的"timestamp"或时间点实例,就不能使用reflect.DeepEqual
。你必须重新设计,无法强制reflect.DeepEqual
按照你的要求进行比较。
英文:
> Could anyone tell me what might be going wrong in [...] reflect.DeepEqual [...] timestamp comparison
reflect.DeepEqual
reports whether two things are deeply equal, it doesn't care about "timestamps". Several "timestamps" representing the same instance in time might (actually do) have different representations as a time.Time
.
You cannot use reflect.DeepEqual
to compare time.Time
values if you are interested in comparing the "timestamp" or instance in time that a time.Time
represents. You must redesign, there is no way to force reflect.DeepEqual
to do what you want.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论