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

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

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

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 ""
}