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

如何在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?

图片转代码服务由CSDN问答提供 功能建议

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

  //我的很好的描述
func myFunc(){...} 
   
 
 

我想拥有我的非常好的描述

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

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

文档中是否存在类似内容? 我可以解析原始的go文件。 有快捷键吗?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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 ""
    }
    
    打赏 评论

相关推荐 更多相似问题