如何在 golang 中获取 func 文档?

如何在 go 代码中获取 func 描述?


// My very nice description

func myFunc() { ... }

我想要My very nice description。


获取函数的名称非常简单:


runtime.FuncForPC(reflect.ValueOf(myFunc).Pointer()).Name()

文档有类似的东西吗?我解析原go文件就可以了。那里有捷径吗?


一只斗牛犬
浏览 128回答 2
2回答

慕妹3146593

使用go/doc包从源代码中提取文档。以防万一有人需要代码,我会把它贴在这里。它可能仍然有点难看,但适合我的场景。您可以根据自己的需要进行调整。package funcreaderimport (    "go/ast"    "go/doc"    "go/parser"    "go/token"    "path/filepath"    "reflect"    "runtime"    "strings")// Get the name and path of a funcfunc 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 funcfunc 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 ""}

慕姐8265434

您可以使用 godoc 工具生成文档。
打开App,查看更多内容
随时随地看视频慕课网APP