Kyaw Myint Thein
Kyaw Myint Thein

Reputation: 540

How to assert ast.TypeSpec to int type in Golang?

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")
}

Upvotes: 2

Views: 1070

Answers (1)

Thundercat
Thundercat

Reputation: 120951

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.

Upvotes: 4

Related Questions