在Golang中,通过反射来识别符文类型是否可能?

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

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
因此,如果你需要区分runeint32,你需要使用其他方法,在代码中使用条件检查来处理它们。

英文:

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.

huangapple
  • 本文由 发表于 2023年7月2日 22:31:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76599379.html
匿名

发表评论

匿名网友

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

确定