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

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

Go - package ast : find package in file

问题

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

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

我正在寻找一种使用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.

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
}

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而不是一个包:

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

英文:

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

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

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:

确定