[英]Go - How can I check for type equality?
Say I have the following code: 说我有以下代码:
var x interface{}
y := 4
x = y
fmt.Println(reflect.TypeOf(x))
This will print int as the type. 这将打印int作为类型。 My question is how can I test for the type?
我的问题是如何测试类型? I know there is the type switch which does this, so I could do:
我知道有这样的类型开关,所以我可以这样做:
switch x.(type) {
case int:
fmt.Println("This is an int")
}
But if I only want to check for just one specific type the switch seems like the wrong tool. 但如果我只想检查一个特定的类型,那么交换机似乎是错误的工具。 Is there a more direct method of doing this like
是否有更直接的方法来做到这一点
reflect.TypeOf(x) == int
or is the type switch the way to go? 或类型开关的方式去?
Type assertions return two values .. the first is the converted value, the second is a bool indicating if the type assertion worked properly. 类型断言返回两个值..第一个是转换后的值,第二个是bool,指示类型断言是否正常工作。
So you could do this: 所以你可以这样做:
_, ok := x.(int)
if ok {
fmt.Println("Its an int")
} else {
fmt.Println("Its NOT an int")
}
..or, shorthand: ..或者,速记:
if _, ok := x.(int); ok {
fmt.Println("Its an int")
}
In Effective Go you can find a really simple example of what you're trying to achieve. 在Effective Go中,您可以找到一个非常简单的示例,说明您要实现的目标。
var t interface{}
t = functionOfSomeType()
switch t := t.(type) {
default:
fmt.Printf("unexpected type %T", t) // %T prints whatever type t has
case bool:
fmt.Printf("boolean %t\n", t) // t has type bool
case int:
fmt.Printf("integer %d\n", t) // t has type int
case *bool:
fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
case *int:
fmt.Printf("pointer to integer %d\n", *t) // t has type *int
}
If you have a single type that you have to check, use a simple if , otherwise use a switch for better readability. 如果您需要检查一种类型,请使用简单的if ,否则请使用开关以提高可读性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.