go – How do I list the public methods of a package in golang-ThrowExceptions

Exception or error:

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")
}
How to solve:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *