英文:
Get package name for a function in go language
问题
要获取Go语言中函数的包名,可以使用反射(reflection)来实现。以下是一个示例代码:
package main
import (
"fmt"
"reflect"
)
func GetPackageName(f interface{}) string {
fullName := reflect.TypeOf(f).String()
pkgName := fullName[:strings.Index(fullName, ".")]
return pkgName
}
func main() {
pkgName := GetPackageName(fmt.Println)
fmt.Println(pkgName) // 输出:fmt
pkgName = GetPackageName(http.StatusText)
fmt.Println(pkgName) // 输出:net/http
}
在上述代码中,GetPackageName
函数接受一个函数作为参数,并使用反射获取函数的类型信息。然后,通过字符串处理,提取出包名部分并返回。你可以将需要获取包名的函数作为参数传递给 GetPackageName
函数,然后获取对应的包名。
英文:
I need to get the package name for a function in Go.
For example if Println
is the input then the output must be fmt
. If StatusText
is the input then the output must be net/http
.
What is the right method to achieve this?
答案1
得分: 1
根据你的评论,似乎你正在寻找一个类似于godoc
的命令行工具,但是不像godoc net/http StatusText
那样需要输入完整的路径,而是希望能够只使用doc StatusText
,然后它会为你找到http.StatusText
(以及其他foo.StatusText
函数)。
Rob Pike的doc
工具可以完全满足你的需求,它会查找你的GOPATH
中的所有包。(尽管它的输出不仅仅是包名,而是你原始问题所要求的)。
你可以使用以下命令获取并安装doc
:go install robpike.io/cmd/doc
或者,你实际上是在寻找一种从Go代码内部获取这些信息而不是从命令行获取的方法吗?
英文:
From your comment it seems that you're looking for a command line tool like godoc
but which instead of requiring something like godoc net/http StatusText
you want to be able to just use doc StatusText
and have it find http.StatusText
for you (and possibly other foo.StatusText
functions as well).
Rob Pike's doc
tool can do exactly that, it looks through all packages in your GOPATH
. (Although it's output isn't just the package name as your original question asks for).
You can get and install doc
with: go install robpike.io/cmd/doc
Or are you actually looking for a way of getting this information from within Go code rather than the command line?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论