dongzhuang5741 2019-02-06 16:42
浏览 160
已采纳

如何在golang中获取func文档?

How can I get the func description within go code?

// My very nice description
func myFunc() { ... }

I'd like to have My very nice description.

Getting the name of a func is pretty straight forward:

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

Is there something similar for the documentation? It would be ok for me to parse the original go file. Any shortcuts there?

  • 写回答

3条回答 默认 最新

  • duanlei2150 2019-02-06 17:06
    关注

    Use the go/doc package to extract documentation from source code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • duanguochong0397 2019-02-06 16:53
    关注

    You can use the godoc tool to generate documentation.

    Check the following link https://blog.golang.org/godoc-documenting-go-code

    It should give what you are looking for

    评论
  • douzhi6365 2019-02-08 08:35
    关注

    Just in case someone needs the code, I'll post it here. It may be a bit ugly still, but works fine for my scenarios. You may adjust it upon your own needs.

    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 ""
    }
    
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 powerbulider 导入excel文件,显示不完整
  • ¥20 #关于multisim绘图遇到的问题
  • ¥15 用keil调试程序保证结果进行led相关闪烁
  • ¥15 paddle训练自己的数据loss降不下去
  • ¥20 用matlab的pdetool解决以下三个问题
  • ¥15 单个福来轮的平衡与侧向滑动是如何做到的?
  • ¥15 嵌入式Linux固件,能直接告诉我crc32校验的区域在哪不,内核的校验我已经找到了,uboot没有
  • ¥20 h3c静态路要求有详细过程
  • ¥15 调制识别中输入为时频图,星座图,眼图等
  • ¥15 数据结构C++的循环、随机数问题