Go – package ast:在文件中查找包

huangapple go评论122阅读模式
英文:

Go - package ast : find package in file

问题

我正在使用ast包解析文件。我已经查看了一段时间的文档,但找不到一种方法来确定一个标记是否是包声明,例如文件开头的package main

  1. func find_package(node ast.Node) bool {
  2. switch x := node.(type) {
  3. // 这可以用于*ast.Ident或*ast.FuncDecl,但不能用于*ast.Package
  4. case *ast.Package:
  5. fmt.Print(x.Name)
  6. }
  7. return true
  8. }

我正在寻找一种使用ast包的简洁方法来实现这一点,我几乎确定我只是在文档中漏掉了某些内容。

英文:

I am parsing files with the ast package.<br>
I have been looking at the documentation for a bit and I can't find a way to determine if a token is a package declaration, e.g: package main at the beggining of the file.

  1. func find_package(node ast.Node) bool {
  2. switch x := node.(type) {
  3. // This works with *ast.Ident or *ast.FuncDecl ... but not
  4. // with *ast.Package
  5. case *ast.Package:
  6. fmt.Print(x.Name)
  7. }
  8. return true
  9. }

I am looking for a clean way to do this with the ast package, I am almost sure I am just missing something in the documentation.

答案1

得分: 1

基本上,看起来你需要寻找一个File而不是一个包:

  1. func find_package(node ast.Node) bool {
  2. switch x := node.(type) {
  3. case *ast.File:
  4. fmt.Print(x.Name)
  5. }
  6. return true
  7. }

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

英文:

So basically, it seems like you have to look for a File instead of a package:

  1. func find_package(node ast.Node) bool {
  2. switch x := node.(type) {
  3. case *ast.File:
  4. fmt.Print(x.Name)
  5. }
  6. return true
  7. }

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

huangapple
  • 本文由 发表于 2016年11月1日 19:41:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/40359350.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定