检查Go中结构体的类型

huangapple go评论83阅读模式
英文:

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))
}

Playground


更简化的写法:

_, isTest := v.(Test)

Playground


你可以参考语言规范以获取技术解释。

英文:

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))
}

Playground


And, more simplified:

_, isTest := v.(Test)

Playground


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?

huangapple
  • 本文由 发表于 2017年7月13日 04:57:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/45067382.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定