function - 识别给定包/文件中的函数
问题描述
我想做什么:
我正在尝试编写一个程序来读取.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) }
我希望能够在这个文件中识别和存储主要和检查功能并存储它们。
非常感谢
解决方案
使用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)
}
推荐阅读
- pandas - 在熊猫数据框中选择具有最小值和最大值的行
- svn - 提交时出现 SVN 错误:“svnlook:路径 'path/to/dir' 不是文件”
- css - SVG 虚线动画在 Chrome 中不起作用
- android - 如何防止视频录制(在录制时录制黑色视频),如 hotstar 应用程序
- spring - 多对多映射方法有什么区别
- java - 二进制内容响应 - 文件名无效?
- python - 将 HTML 输入中的变量分配给 Python/Flask
- ubuntu - 包含文本和图像的页面的 OCRing pdf
- nix - 如何从 nix 表达式文件中安装 nix-env 派生?
- python-3.x - keras 嵌入层导致 tensorflow.python.framework.errors_impl.InvalidArgumentError: