Avatar ·

Go中time.Time的零值是什么以及如何检查时间变量是否为空?

大家好!我刚开始学习Go,在使用time包时遇到了一个不太明白的情况。

我有一个结构体,其中一个字段是日期和时间。有时这个字段可能未被设置(其他语言中的null)。在PHP或JavaScript中,我只需检查null,但在Go中没有这种便利。我尝试使用nil,但编译器报错了。

以下是我的代码示例:

package main

import (
    "fmt"
    "time"
)

type Event struct {
    Name      string
    CreatedAt time.Time
    UpdatedAt time.Time // 可能未被设置
}

func main() {
    e := Event{
        Name: "测试事件",
        // 未设置UpdatedAt
    }
    
    // 尝试检查UpdatedAt是否已设置
    if e.UpdatedAt == nil {  // 编译错误
        fmt.Println("UpdatedAt未设置")
    }
    
    fmt.Println(e.UpdatedAt) // 输出:0001-01-01 00:00:00 +0000 UTC
}