我希望time.Now().In(location)對(duì)象在同一時(shí)刻比較為相同,即使location對(duì)象不同,只要location對(duì)象是使用相同的name字符串創(chuàng)建的。為什么這種期望不成立?package mainimport ( "fmt" "time" "log")func main() { const USPacificTimeZone = "US/Pacific" location, err := time.LoadLocation(USPacificTimeZone) if err != nil { log.Fatal(fmt.Sprintf("Couldn't load timezone: %v", err)) } // Exactly the same as location above, just a new instance location2, err := time.LoadLocation(USPacificTimeZone) if err != nil { log.Fatal(fmt.Sprintf("Couldn't load timezone: %v", err)) } now := time.Now() fmt.Printf("Times using same location object: %v\n", now.In(location) == now.In(location)) // prints: Times using same location object: true // Using (the identical) location2 causes the times to be different??? fmt.Printf("Times using different location objects: %v\n", now.In(location) == now.In(location2)) // prints: Times using different location objects: false}
1 回答

阿晨1998
TA貢獻(xiàn)2037條經(jīng)驗(yàn) 獲得超6個(gè)贊
使用Equal方法比較時(shí)間點(diǎn):
fmt.Printf("Times using different location objects: %v\n", now.In(location).Equal(now.In(location2))) // prints true
Time 類型文檔描述了將 Time 值與 進(jìn)行比較的陷阱 ==
:
請(qǐng)注意,Go == 運(yùn)算符不僅比較時(shí)間瞬間,還會(huì)比較位置和單調(diào)時(shí)鐘讀數(shù)。因此,如果沒有首先保證為所有值設(shè)置了相同的位置,時(shí)間值不應(yīng)用作地圖或數(shù)據(jù)庫鍵,這可以通過使用 UTC 或本地方法來實(shí)現(xiàn),并且單調(diào)時(shí)鐘讀數(shù)已被剝離設(shè)置 t = t.Round(0)。一般來說,更喜歡 t.Equal(u) 而不是 t == u,因?yàn)?t.Equal 使用可用的最準(zhǔn)確的比較,并正確處理只有一個(gè)參數(shù)具有單調(diào)時(shí)鐘讀數(shù)的情況。
- 1 回答
- 0 關(guān)注
- 107 瀏覽