获取Go语言中函数的包名

huangapple go评论110阅读模式
英文:

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中的所有包。(尽管它的输出不仅仅是包名,而是你原始问题所要求的)。

你可以使用以下命令获取并安装docgo 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?

huangapple
  • 本文由 发表于 2015年7月7日 17:17:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/31264507.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定