如何获取golang中的func文档?
时间:2024-04-10
浏览:380
作者:佚名
积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《如何获取golang中的func文档?》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~
问题内容
如何获取 go 代码中的 func 描述?
// my very nice description
func myfunc() { ... }
我想要 我非常好的描述 。
获取函数的名称非常简单:
runtime.FuncForPC(reflect.ValueOf(myFunc).Pointer()).Name()
文档中有类似的内容吗?我解析原始的 go 文件就可以了。有什么捷径吗?
解决方案
使用 go/doc 包从源代码中提取文档。
以防万一有人需要代码,我会将其发布在这里。它可能仍然有点难看,但对于我的场景来说效果很好。您可以根据自己的需要进行调整。
package funcreader
import (
"go/ast"
"go/doc"
"go/parser"
"go/token"
"path/filepath"
"reflect"
"runtime"
"strings"
)
// Get the name and path of a func
func FuncPathAndName(f interface{}) string {
return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
}
// Get the name of a func (with package path)
func FuncName(f interface{}) string {
splitFuncName := strings.Split(FuncPathAndName(f), ".")
return splitFuncName[len(splitFuncName)-1]
}
// Get description of a func
func FuncDescription(f interface{}) string {
fileName, _ := runtime.FuncForPC(reflect.ValueOf(f).Pointer()).FileLine(0)
funcName := FuncName(f)
fset := token.NewFileSet()
// Parse src
parsedAst, err := parser.ParseFile(fset, fileName, nil, parser.ParseComments)
if err != nil {
log.Fatal(err)
return ""
}
pkg := &ast.Package{
Name: "Any",
Files: make(map[string]*ast.File),
}
pkg.Files[fileName] = parsedAst
importPath, _ := filepath.Abs("/")
myDoc := doc.New(pkg, importPath, doc.AllDecls)
for _, theFunc := range myDoc.Funcs {
if theFunc.Name == funcName {
return theFunc.Doc
}
}
return ""
}文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《如何获取golang中的func文档?》文章吧,也可关注golang学习网公众号了解相关技术文章。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
12.01
12.01
热门专题
