How do I list the public methods of a package in golang [duplicate]

女生的网名这么多〃 提交于 2020-01-11 06:52:07

问题


How to list the package's public methods in golang?

main.go

package main

func main() {
// list all public methods in here
}

libs/method.go

package libs

func Resut1() {
    fmt.Println("method Result1")
}

func Resut2() {
    fmt.Println("method Result2")
}

回答1:


I can't answer with a 100% confidence, but I don't think this is possible to do in Go, at least quite as described. This discussion is rather old, but it describes the basic problem - just importing a package doesn't guarantee that any methods from the package are actually there. The compiler actually tries to remove every unused function from the package. So if you have a set of "Result*" methods in another package, those methods won't actually be there when you call the program unless they are already being used.

Also, if take a look at the runtime reflection library, you'll note the lack of any form of package-level analysis.


Depending on your use case, there still might be some things you can do. If you just want to statically analyze your code, you can parse a package and get the full range of function delcarations in the file, like so:

import (
    "fmt"
    "go/ast"
    "go/parser"
    "go/token"
    "os"
)

const subPackage := "sub"

func main() {
    set := token.NewFileSet()
    packs, err := parser.ParseDir(set, subPackage, nil, 0)
    if err != nil {
        fmt.Println("Failed to parse package:", err)
        os.Exit(1)
    }

    funcs := []*ast.FuncDecl{}
    for _, pack := range packs {
        for _, f := range pack.Files {
            for _, d := range f.Decls {
                if fn, isFn := d.(*ast.FuncDecl); isFn {
                    funcs = append(funcs, fn)
                }
            }
        }
    }

    fmt.Printf("all funcs: %+v\n", funcs)
}

This will get all function delcarations in the stated subpackage as an ast.FuncDecl. This isn't an invokable function; it's just a representation of the source code of it.

If you wanted to do anything like call these functions, you'd have to do something more sophisticated. After gathering these functions, you could gather them and output a separate file that calls each of them, then run the resulting file.



来源:https://stackoverflow.com/questions/41629293/how-do-i-list-the-public-methods-of-a-package-in-golang

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!