我有以下用于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")
}发布于 2016-10-27 00:20:29
AST中的类型表示用于声明类型的语法,而不是实际的类型。例如:
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,但不能可靠地执行此操作:
if id, ok := ts.Type.(*ast.Ident); ok {
if id.Name == "int" {
// it might be an int
}
}对于以下情况,代码不正确:
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。
https://stackoverflow.com/questions/40266003
复制相似问题