2016-10-26 27 views
1

私はGolangドキュメントの解析に次のコードを使用しています。 "ts"はast.TypeSpecです。私はStructTypeなどをチェックすることができますが、ts.Typeは "int"です。 intやその他の基本型に対してどのようにアサートすることができますか?Golangのint型にast.TypeSpecをアサートする方法は?

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

答えて

2

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 

さまざまな構文がどのように表現されているかを理解しようとすると、サンプルASTを印刷すると便利です。 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

+0

この場合、私はbt:= fmt.Sprintf( "%s"、ts.Type)を使うことができると思います。どれが良いか分かりません。 –

+0

通常、fmt.Sprintfが印刷するものよりも、ASTを検査するためにメソッドとフィールドを使用する方が良いです。 –

関連する問題