反射:是否可以获取底层的类型信息?

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

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.

huangapple
  • 本文由 发表于 2016年1月29日 09:18:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/35075278.html
匿名

发表评论

匿名网友

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

确定