reflect.DeepEqual在时间戳比较上不起作用。

huangapple go评论82阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年3月23日 23:20:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75824869.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定