Golang检查数据是否是time.Time

时间:2017-01-05 11:10:48

标签: go time types

if条件下,我试图了解我的数据类型是否为time.Time

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

1 个答案:

答案 0 :(得分:6)

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

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
}

如果您不需要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
}

另请注意,time.Time*time.Time类型不同。如果包含指向time.Time的指针,则需要将其作为其他类型进行检查。

相关问题