英文:
How to assert ast.TypeSpec to int type in Golang?
问题
我有以下用于解析Golang文档的代码。"ts"是ast.TypeSpec。我可以检查StructType等。但是,ts.Type是"int"。我如何断言为int和其他基本类型?
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")
}
英文:
I have following code for Golang docs parsing. "ts" is ast.TypeSpec. I can check StructType and etc. But, ts.Type is "int". How can I assert for int and other basic type?
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")
}
答案1
得分: 4
AST中的类型表示用于声明类型的语法,而不是实际的类型。例如:
type t struct { }
var a int // TypeSpec.Type 是 *ast.Ident
var b struct { } // TypeSpec.Type 是 *ast.StructType
var c t // TypeSpec.Type 是 *ast.Ident,但 c 变量是一个结构类型
在尝试理解不同语法如何表示时,打印示例AST是很有帮助的。运行此程序以查看示例。
以下代码在大多数情况下会检查整数,但不可靠:
if id, ok := ts.Type.(*ast.Ident); ok {
if id.Name == "int" {
// 可能是一个整数
}
}
以下情况下该代码不正确:
type myint int
var a myint // a 的底层类型是 int,但它没有声明为 int
type int anotherType
var b int // b 是 anotherType,而不是预声明的 int 类型
要可靠地找到源代码中的实际类型,请使用 go/types 包。该包的教程可供参考。
英文:
The types in the AST represent the syntax used to declare the type and not the actual type. For example:
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
I find it's helpful to print example ASTs when trying to understand how different syntax is represented. Run this program to see an example.
This code will check for ints in most cases, but does not do so reliably:
if id, ok := ts.Type.(*ast.Ident); ok {
if id.Name == "int" {
// it might be an int
}
}
The code is not correct for the following cases:
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
To reliably find the actual types in the source, use the go/types package. A tutorial on the package is available.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论