英文:
reflect: Is it possible to get the underlying typed type information?
问题
我正在将一个程序从go/ast
转换为reflect
。为了通过测试,我需要获取顶层类型信息以及底层类型(如果底层类型不是内置类型)。
在下面的示例中,程序是否可以知道 main.T 的底层类型是 main.TT?
package main
import "fmt"
import "reflect"
func main() {
type TT int
type T TT
x := T(0)
fmt.Println(reflect.TypeOf(x))
}
输出:
main.T
英文:
I'm porting a program from go/ast
to reflect
. In order to pass the tests I need to get not only the top type information but also the underlying type if the underlying type is not built-in.
In the example below, is it possible for a program to know that the underlying type of main.T is main.TT?
package main
import "fmt"
import "reflect"
func main() {
type TT int
type T TT
x := T(0)
fmt.Println(reflect.TypeOf(x))
}
Output:
main.T
答案1
得分: 2
main.T
的底层类型是int
,而不是main.TT
。反射包不知道main.T
是用main.TT
声明的。
关于底层类型,规范中有以下说明:
每个类型T都有一个底层类型:如果T是预声明的布尔、数值或字符串类型,或者是类型字面量,则相应的底层类型就是T本身。否则,T的底层类型是T在其类型声明中引用的类型的底层类型。
type T1 string type T2 T1 type T3 []T1 type T4 T3
字符串、T1和T2的底层类型都是string。[]T1、T3和T4的底层类型都是[]T1。
英文:
The underlying type of main.T
is int
, not main.TT
. The reflect package has no knowledge that main.T
was declared with main.TT
.
Here's what the specification has to say about underlying types:
>Each type T has an underlying type: If T is one of the predeclared boolean, numeric, or string types, or a type literal, the corresponding underlying type is T itself. Otherwise, T's underlying type is the underlying type of the type to which T refers in its type declaration.
>
> type T1 string
> type T2 T1
> type T3 []T1
> type T4 T3
>
> The underlying type of string, T1, and T2 is string. The underlying type of []T1, T3, and T4 is []T1.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论