Golang检查数据是否是time.Time

Dob*_*oby 1 time types go

在一个if条件下,我试图知道我的数据类型是否是time.Time.

获取res.Datas[i]数据类型并在if循环中检查它的最佳方法是什么?

icz*_*cza 6

假设type res.Datas[i]不是具体类型而是接口类型(例如interface{}),只需使用类型断言:

if t, ok := res.Datas[i].(time.Time); ok {
    // it is of type time.Time
    // t is of type time.Time, you can use it so
} else {
    // not of type time.Time, or it is nil
}
Run Code Online (Sandbox Code Playgroud)

如果您不需要该time.Time值,您只想知道接口值是否包含time.Time:

if _, ok := res.Datas[i].(time.Time); ok {
    // it is of type time.Time
} else {
    // not of type time.Time, or it is nil
}
Run Code Online (Sandbox Code Playgroud)

还要注意类型time.Time*time.Time不同.如果指针time.Time被包装,则需要将其作为不同类型进行检查.