2014-04-14 58 views
55

錯誤狀態,我試圖返回nil,這引發錯誤:什麼是時間的「零」值?

cannot use nil as type time.Time in return argument 

什麼是time.Timezero價值?

+12

而且您可以使用'IsZero()'來檢測零時間。 – Matt

回答

60

調用一個空的time.Time結構文字將返回Go的零日期。因此,下面的打印語句:

fmt.Println(time.Time{}) 

輸出是:

0001-01-01 00:00:00 +0000 UTC 

爲了完整起見,official documentation明確規定:

The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC.

+5

「傳遞任何參數」使它聽起來像一個函數調用。這是一個沒有指定字段的結構字面值。 X {}是任何X的struct X的零值。 –

+0

@RussCox我不認爲這是真的。在我的情況下,我有一段時間。在我的結構中有'omitempty'屬性的時間。如果我沒有設置該值,它會自動設置爲0001-01-01 00:00:00 + 0000 UTC,而不是被忽略。 –

+0

@GauravOjha請參閱[Golang JSON omitempty With time.Time Field](http://stackoverflow.com/questions/32643815/golang-json-omitempty-with-time-time-field/32646035#32646035)。 – icza

125

Y您應該使用Time.IsZero()函數代替:

func (Time) IsZero 

func (t Time) IsZero() bool 
IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC. 
+16

這應該是被接受的答案。 –

+0

事實上,如果比較給定的時間值是否爲零,這實際上應該使用什麼。 –