gpt4 book ai didi

Golang 检查数据是否为 ​​time.Time

转载 作者:IT王子 更新时间:2023-10-29 01:51:01 27 4
gpt4 key购买 nike

if 条件下,我想知道我的数据类型是否为 time.Time

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

最佳答案

假设 res.Datas[i] 的类型不是具体类型而是接口(interface)类型(例如 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 值,您只想判断接口(interface)值是否包装了一个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 的指针被包装,您需要将其检查为不同的类型。

关于Golang 检查数据是否为 ​​time.Time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41483505/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com