首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Golang中将ast.TypeSpec断言为int类型?

如何在Golang中将ast.TypeSpec断言为int类型?
EN

Stack Overflow用户
提问于 2016-10-26 23:13:36
回答 1查看 625关注 0票数 2

我有以下用于Golang文档解析的代码。"ts“是ast.TypeSpec。我可以检查StructType等。但是,ts.Type是"int“。如何为int和其他基本类型断言?

代码语言:javascript
复制
ts, ok := d.Decl.(*ast.TypeSpec)
switch ts.Type.(type) {
case *ast.StructType:
    fmt.Println("StructType")
case *ast.ArrayType:
    fmt.Println("ArrayType")
case *ast.InterfaceType:
    fmt.Println("InterfaceType")
case *ast.MapType:
    fmt.Println("MapType")
}
EN

回答 1

Stack Overflow用户

发布于 2016-10-27 00:20:29

AST中的类型表示用于声明类型的语法,而不是实际的类型。例如:

代码语言:javascript
复制
type t struct { }

var a int          // TypeSpec.Type is *ast.Ident
var b struct { }   // TypeSpec.Type is *ast.StructType
var c t            // TypeSpec.Type is *ast.Ident, but c variable is a struct type

我发现在试图理解不同的语法如何表示时,打印示例ASTs是很有帮助的。Run this program to see an example

在大多数情况下,此代码将检查int,但不能可靠地执行此操作:

代码语言:javascript
复制
if id, ok := ts.Type.(*ast.Ident); ok {
    if id.Name == "int" {
        // it might be an int
    }
}

对于以下情况,代码不正确:

代码语言:javascript
复制
type myint int
var a myint          // the underlying type of a is int, but it's not declared as int

type int anotherType 
var b int            // b is anotherType, not the predeclared int type

要可靠地找到源代码中的实际类型,请使用go/types包。A tutorial on the package is available

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40266003

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档