Listing Public Methods of a Package in Go
Question:
How is it possible to enumerate the public methods of a package in Go? Consider the following code structure:
main.go:
package main func main() { // list public methods in here }
libs/method.go:
package libs func Result1() { fmt.Println("method Result1") } func Result2() { fmt.Println("method Result2") }
Answer:
Regrettably, Go lacks a direct feature for this request. When a package is imported, the compiler may remove unused methods during optimization. Thus, the mere importing of a package does not guarantee the presence of all methods.
Alternatives:
Static Analysis:
You can parse the package's source code and extract function declarations using Go's reflection library. Consider the following example:
import ( "fmt" "go/parser" "go/token" ) func main() { fileset := token.NewFileSet() packages, err := parser.ParseDir(fileset, "./libs", nil, 0) if err != nil { fmt.Println("Parsing failed:", err) return } methods := []string{} for _, p := range packages { // Get all methods in each source file. for _, f := range p.Files { for _, dec := range f.Decls { if fn, ok := dec.(*parser.FuncDecl); ok && fn.Name.IsExported() { methods = append(methods, fn.Name.String()) } } } } fmt.Println("Exported methods in package 'libs':", methods) }
Note: This approach only provides function declarations, not their implementations.
Dynamic Reflection:
Alternatively, you could use Go's reflect package at runtime to inspect the methods of a value. However, this requires having an initialized instance of the type in question.
Remember that these approaches have limitations and may not be suitable for all use cases.
The above is the detailed content of How to List Public Methods of a Go Package?. For more information, please follow other related articles on the PHP Chinese website!