英文:
Go - How can I check for type equality?
问题
你可以使用反射包中的reflect.TypeOf
函数来获取变量的类型,并与目标类型进行比较。例如,你可以使用以下代码来检查变量x
是否为int
类型:
if reflect.TypeOf(x) == reflect.TypeOf(0) {
fmt.Println("This is an int")
}
这将打印出"This is an int",如果x
的类型是int
的话。使用reflect.TypeOf(x)
可以获取变量x
的实际类型,然后将其与reflect.TypeOf(0)
进行比较,其中reflect.TypeOf(0)
表示int
类型的反射对象。
请注意,使用反射可能会导致性能下降,因此在性能要求较高的情况下,最好使用类型断言或类型切换来进行类型检查。
英文:
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. 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?
答案1
得分: 16
类型断言返回两个值,第一个是转换后的值,第二个是一个布尔值,指示类型断言是否成功。
所以你可以这样做:
_, ok := x.(int)
if ok {
fmt.Println("它是一个整数")
} else {
fmt.Println("它不是一个整数")
}
..或者,简写形式:
if _, ok := x.(int); ok {
fmt.Println("它是一个整数")
}
英文:
Type assertions return two values .. the first is the converted value, the second is a bool indicating if the type assertion worked properly.
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")
}
<kbd>See it in the playground</kbd>
答案2
得分: 4
我刚刚根据这个链接找到了另一种方法来完成这个任务:
if _, ok := x.(int); ok {
fmt.Println("这是一个整数")
}
英文:
I just figured out another way of doing this based on this:
if _, ok := x.(int); ok {
fmt.Println("This is an int")
}
答案3
得分: 0
在Effective Go中,你可以找到一个非常简单的例子,展示了你想要实现的内容。
var t interface{}
t = functionOfSomeType()
switch t := t.(type) {
default:
fmt.Printf("unexpected type %T", t) // %T 打印出 t 的类型
case bool:
fmt.Printf("boolean %t\n", t) // t 的类型是 bool
case int:
fmt.Printf("integer %d\n", t) // t 的类型是 int
case *bool:
fmt.Printf("pointer to boolean %t\n", *t) // t 的类型是 *bool
case *int:
fmt.Printf("pointer to integer %d\n", *t) // t 的类型是 *int
}
如果你只需要检查一个类型,可以使用简单的 if 语句,否则可以使用 switch 语句以提高可读性。
英文:
In Effective Go you can find a really simple example of what you're trying to achieve.
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论