首页 > 解决方案 > 识别给定包/文件中的函数

问题描述

我想做什么:

我正在尝试编写一个程序来读取.go文件并将其存储为,比如说一个字符串。之后我想以某种方式识别该文件中的所有函数并将它们分别存储,例如在一个函数片中。后者是我卡住的地方。我尝试使用正则表达式匹配函数,但以这种方式匹配每个单独的函数似乎非常困难。

所以基本上我要求的是一种方法来获取给定文件中的每个单独的函数,并以某种方式将其存储在容器中。

示例代码

func check(e error) {
if e != nil {
    panic(e)
}

func main() {
f, err := ioutil.ReadFile("../test.txt")
check(err)
s := string(f)
SearchFunctions(s) }

我希望能够在这个文件中识别和存储主要检查功能并存储它们。

非常感谢

标签: functionparsinggo

解决方案


使用go/parser 包将源解析为 AST。使用go/ast 包 搜索函数。

src := `package example

    func myfunction() {
        log.Fatal("blah")
    }
    func aDifferentFunction() {
         panic("blah")
    }`

// Parse the file.
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "example.go", src, 0)
if err != nil {
    log.Fatal(err)
}

var functions []*ast.FuncDecl

// Walk the AST looking for functions.
ast.Inspect(f, func(n ast.Node) bool {
    if n, ok := n.(*ast.FuncDecl); ok {
        functions = append(functions, n)
    }
    return true
})

for _, n := range functions {
    fmt.Printf("\n---\nfound function %s at %s\n", n.Name.Name, fset.Position(n.Pos()))
    printer.Fprint(os.Stdout, fset, n)
}

在操场上运行它


推荐阅读