英文:
Check type of struct in Go
问题
我正在尝试检查Go语言中结构体的类型。这是我能想到的最好的方法。有没有更好的方法来做到这一点,最好不需要初始化一个结构体?
package main
import (
"fmt"
"reflect"
)
type Test struct{
foo int
}
func main() {
t := Test{5}
fmt.Println(reflect.TypeOf(t) == reflect.TypeOf(Test{}))
}
英文:
I'm trying to check the type of a struct in Go. This was the best way I could come up with. Is there a better way to do it, preferably without initializing a struct?
package main
import (
"fmt"
"reflect"
)
type Test struct{
foo int
}
func main() {
t := Test{5}
fmt.Println(reflect.TypeOf(t) == reflect.TypeOf(Test{}))
}
答案1
得分: 22
类型断言:
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)
你可以参考语言规范以获取技术解释。
英文:
Type assertions:
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))
}
And, more simplified:
_, isTest := v.(Test)
You can refer to the language specification for a technical explanation.
答案2
得分: 5
你可以将一个"typed"的nil
指针值传递给reflect.TypeOf()
,然后调用Type.Elem()
来获取指向值的类型。这不会分配或初始化该类型的值,因为只使用了一个nil
指针值:
fmt.Println(reflect.TypeOf(t) == reflect.TypeOf((*Test)(nil)).Elem())
在Go Playground上试一试。
附注:这是一个完全重复的问题,但找不到原始问题。
英文:
You may pass a "typed" nil
pointer value to reflect.TypeOf()
, and call Type.Elem()
to get the type of the pointed value. This does not allocate or initialize a value of the type (in question), as only a nil
pointer value is used:
fmt.Println(reflect.TypeOf(t) == reflect.TypeOf((*Test)(nil)).Elem())
Try it on the Go Playground.
P.S. This is an exact duplicate, but can't find the original.
答案3
得分: 1
你可以将t赋值给一个空接口变量,并检查其类型,不一定需要编写一个函数来进行检查。
var i interface{} = t
v, ok := i.(Test)
//v = Test结构体的具体值
//ok = (t)是否为Test结构体的类型?
英文:
You can simply assign t to an empty interface variable and check its type
and you don't need to necessarily write a function to check this out.
var i interface{} = t
v, ok := i.(Test)
//v = concrete value of Test struct
//ok = is (t) a type of the Test struct?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论