如何在golang中列出包的公共方法 [英] How do I list the public methods of a package in golang
问题描述
如何在golang中列出包的公共方法?
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")
}
推荐答案
我无法百分百地回答,但我认为至少在上述情况下,在Go中是不可能做到的. 此讨论虽然年代久远,但它描述了基本问题-仅导入包并不能保证包中的任何方法都确实存在.编译器实际上试图从包中删除所有未使用的函数.因此,如果在另一个程序包中有一组"Result *"方法,则除非您已在使用这些方法,否则在您调用程序时这些方法实际上将不存在.
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)
}
这将以 ast.FuncDecl
.这不是一个可调用的函数;它只是它的源代码的表示形式.
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.
这篇关于如何在golang中列出包的公共方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!