go - 如何以编程方式检索声明给定类型的包路径?
问题描述
我正在寻找一种方法来检索本地安装的包,其中包含给定类型的声明和默认包名称。
IE:
// FindPackagesForType returns the list of possible packages for a given type
func FindPackagesForType(typeName string) []string {
return []string {} // TODO: implement
}
func TestFindPackagesForType(t *testing.T) {
assert.Contains(t, FindPackagesForType("io.Reader"), "io")
assert.Contains(
t,
FindPackagesForType("types.Timestamp"),
"github.com/gogo/protobuf/types",
)
assert.Contains(
t,
FindPackagesForType("types.ContainerCreateConfig"),
"github.com/docker/docker/api/types",
)
}
我可以尝试检索所有已安装的包,并在每个查找声明时通过 AST,但如果有一个解决方案可以更有效地做到这一点,同时还提供对 go 模块的支持,我想使用它。
这样做的原因是为了改进代码生成工具。这个想法是让用户提供类型的名称,并让工具识别最有可能的候选者,就像 goimports 添加缺失的导入一样。
解决方案
您可以使用reflect.TypeOf(any).PkgPath()
获取特定类型的包路径。但是,我们需要传递具有所需类型的对象(而不是您想要的字符串)。
package main
import (
"bytes"
"fmt"
"reflect"
"gopkg.in/mgo.v2/bson"
)
func main() {
var a bytes.Buffer
fmt.Println(FindPackagesForType(a)) // output: bytes
var b bson.M
fmt.Println(FindPackagesForType(b)) // output: gopkg.in/mgo.v2/bson
}
func FindPackagesForType(any interface{}) string {
return reflect.TypeOf(any).PkgPath()
}
推荐阅读
- javascript - textarea onChange 不更新状态
- html - Apple App Store 徽章重定向到移动设备而非桌面设备上的可疑广告
- java - 如何从 JTextField 获取字符串并将其保存在变量中的更新?
- python - 我们可以为 pd.to_numeric 设置特定的列和行吗?
- android - Firestore addSnapshotListener 不起作用
- java - Java中不同类型的连接
- javascript - 对象作为 React 子对象无效(找到:带有键 {arr} 的对象)。如果您打算渲染一组孩子,请改用数组
- scala - scala:如何迭代类型安全配置列表
- python - 当我运行我的代码 SpotifyOauthError: error: invalid_client, error_description: Invalid client 时出现此错误
- typescript - 基于另一个属性值的动态类型属性