How do I list the public methods of a package in g

2019-06-01 02:23发布

问题:

This question already has an answer here:

  • Call functions with special prefix/suffix 2 answers

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 I think 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, I think 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.



回答2:

If you're talking about figuring this out using a command-line, use the go list command. In particular, start with running

go help list

in your terminal.

If you mean doing this in your own Go code at runtime, I beleive this is doable with the help of the standard package reflect.



标签: go reflection