这里有一些关于如何在运行时确定对象类型的现有答案..god help us
if reflect.TypeOf(err) == string {
}
不编译
if reflect.TypeOf(err) == "string" {
}
既不是那个也不是这个:
if reflect.TypeOf(err).Kind() == "string" {
}
我们如何做到这一点?
如果我使用其中一个答案给出的 typeof 函数,我会得到:
最佳答案
比较字符串
if reflect.TypeOf(err).String() == "string" {
fmt.Println("hello")
}
或使用 type assertions
type F = func()
func typeof(v interface{}) string {
switch v.(type) {
case int:
return "int"
case string:
return "string"
case F:
return "F"
//... etc
default:
return "unknown"
}
}
然后
var f F
if typeof(f) == "F"{
fmt.Println("hello F")
}
关于go - 使用反射确定类型是否为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53861831/