英文:
Is it possible to identify the rune type through reflection in Golang?
问题
在Go语言中,当我执行reflect.TypeOf(r)
时,其中r
是一个rune变量,我得到的类型是int32。当我使用类型切换时,我无法区分int32和rune。文档中说:
> rune是int32的别名,在所有方面等同于int32。它被约定用于区分字符值和整数值。
在给出答案之前,我想在这里问一下:在Go语言中,是否有任何方法可以通过反射区分rune和int32?
英文:
In Go, When I do reflect.TypeOf(r)
, where r
is a rune variable, I get the type int32. When I do a type switch, I cannot differentiate int32 from rune. The docs say:
> rune is an alias for int32 and is equivalent to int32 in all ways. It is used, by convention, to distinguish character values from integer values.
Before giving, I just wanted to ask here: is there any way whatsoever to differentiate rune from int32 through reflection in Go?
答案1
得分: 4
Go语言没有提供任何内置机制来使用反射区分它们。reflect.TypeOf()
函数返回底层类型,无论变量是声明为rune
还是int32
,在这种情况下都是int32
。
因此,如果你需要区分rune
和int32
,你需要使用其他方法,在代码中使用条件检查来处理它们。
英文:
The Go language does not provide any built-in mechanism to distinguish between them using reflection. The reflect.TypeOf()
function returns the underlying type, which in this case is int32
, regardless of whether the variable is declared as rune
or int32
.
So if you need to differentiate between rune
and int32
, you will need to use other means, such as conditional checks to handle them differently in your code.
答案2
得分: 1
一个别名将一个标识符绑定到一个类型。标识符rune
引用的是与int32
相同的类型。
在源代码中用于引用类型的标识符在运行时通过反射或任何其他API都不可用。
英文:
An alias binds an identifier to a type. The identifier rune
refers to the same type as int32
.
The identifier used to refer to a type in source code is not available at runtime through reflection or any other API.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论