If statement 将反映转化为可比数据
我希望能够使用If statement 将反映转化为可比数据,if-statement,reflection,go,types,If Statement,Reflection,Go,Types,我希望能够使用reflect比较对象的类型。这是我的密码: package main import ( "fmt" "reflect" ) func main() { tst := "cat" if reflect.TypeOf(tst) == string { fmt.Println("It's a string!") } } 这给了我一个错误类型字符串不是表达式。如何仅使用reflect解决此问题?(无类型开关等)两个简单选项:
reflect
比较对象的类型。这是我的密码:
package main
import (
"fmt"
"reflect"
)
func main() {
tst := "cat"
if reflect.TypeOf(tst) == string {
fmt.Println("It's a string!")
}
}
这给了我一个错误类型字符串不是表达式。如何仅使用reflect解决此问题?(无类型开关等)两个简单选项:
使用种类
:
if reflect.TypeOf(tst).Kind() == reflect.String {
fmt.Println("It's a string!")
}
使用TypeOf
另一个字符串:
if reflect.TypeOf(tst) == reflect.TypeOf("") {
fmt.Println("It's a string!")
}
但是,就个人而言,我更喜欢类型切换或类型检查(即,if uu,ok:=tst.(string);ok{…}
第三个选项:if reflect.TypeOf(tst).Name()=“string”
关于最后一点,如果tst
是接口类型,类型检查难道不起作用吗?@Akavall是的,但如果我们进行此类检查,我假设它已经是接口类型了