2016-11-01 69 views
1

我正在使用ast包解析文件
我一直在尋找了一下文檔,我無法找到一個方法來確定一個標記是一個包聲明e.gpackage main在文件的beggining。Go - 包ast:在文件中找到包

func find_package(node ast.Node) bool { 
    switch x := node.(type) { 
    // This works with *ast.Ident or *ast.FuncDecl ... but not 
    // with *ast.Package 
    case *ast.Package: 
     fmt.Print(x.Name) 
    } 
    return true 
} 

我正在尋找一個乾淨的方式與AST包要做到這一點,我幾乎可以肯定,我只是缺少文檔中的一些東西。

回答

0

所以基本上,好像你必須尋找一個File,而不是包:

func find_package(node ast.Node) bool { 
    switch x := node.(type) { 
    case *ast.File: 
     fmt.Print(x.Name) 
    } 
    return true 
} 

https://golang.org/pkg/go/ast/#File