英文:
Golang check if a data is time.Time
问题
在一个if条件语句中,我想知道我的数据类型是否为time.Time。
在if循环中,获取res.Datas[i]的数据类型并进行检查的最佳方法是什么?
英文:
In a if condition I'm trying to know if my data's type is time.Time.
What is the best way to get the res.Datas[i]'s data type and check it in a if loop ?
答案1
得分: 8
假设res.Datas[i]的类型不是具体类型,而是接口类型(例如interface{}),你可以使用类型断言来判断:
if t, ok := res.Datas[i].(time.Time); ok {
// 它的类型是 time.Time
// t 是 time.Time 类型,你可以使用它
} else {
// 不是 time.Time 类型,或者为 nil
}
如果你只是想判断接口值是否包含了 time.Time 类型,而不需要获取具体的 time.Time 值:
if _, ok := res.Datas[i].(time.Time); ok {
// 它的类型是 time.Time
} else {
// 不是 time.Time 类型,或者为 nil
}
还要注意,time.Time 和 *time.Time 是不同的类型。如果包装的是指向 time.Time 的指针,你需要将其视为不同的类型进行检查。
英文:
Assuming type of res.Datas[i] is not a concrete type but an interface type (e.g. interface{}), simply use a type assertion for this:
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
}
If you don't need the time.Time value, you just want to tell if the interface value wraps a 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
}
Also note that the types time.Time and *time.Time are different. If a pointer to time.Time is wrapped, you need to check that as a different type.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论