我正在尝试检查 Go 中的结构类型。这是我能想到的最好方法。有没有更好的方法,最好不要初始化结构?
package main
import (
"fmt"
"reflect"
)
type Test struct{
foo int
}
func main() {
t := Test{5}
fmt.Println(reflect.TypeOf(t) == reflect.TypeOf(Test{}))
}
最佳答案
类型断言:
package main
import "fmt"
type Test struct {
foo int
}
func isTest(t interface{}) bool {
switch t.(type) {
case Test:
return true
default:
return false
}
}
func main() {
t := Test{5}
fmt.Println(isTest(t))
}
并且,更简化:
_, isTest := v.(Test)
可以引用language specification以获得技术解释。
关于go - 检查 Go 中的结构类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45067382/