使用名称实例化一个包变量。

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

Instantiate a package variable using just the name

问题

我正在尝试为一个包中的一些导出类型添加一些简单的验证代码,该包中充满了常量。我想遍历这个包,找出导出的常量(它们只是字符串),并验证它们的格式。

可以将其想象成我有一个名为flags的包,导出了常量FlagDoAThing = "do-a-thing"。我想遍历该包并查看这些值是什么。


举个例子,我有两个文件:

// main.go
func main() {
	cfg := &packages.Config{
		Mode: packages.NeedTypes,
	}
	pkgs, _ := packages.Load(cfg, "package-inspector/other")
	pkg := pkgs[0]

	scope := pkg.Types.Scope()
	for _, name := range scope.Names() {
		fmt.Println(name)
		obj := scope.Lookup(name)
		fmt.Println(obj)
		fmt.Println("\t", obj.Id(), obj.Type())
	}
}

然后在我的其他包中:

package other

const (
	ExportedOne = "exported_one"
	ExportedTwo = "exported_two"

	privateOne = "private_one"
)

在本地运行时(无法在 playground 中运行),我看到的输出是:

go run main.go
ExportedOne
const package-inspector/other.ExportedOne untyped string
         ExportedOne untyped string
ExportedTwo
const package-inspector/other.ExportedTwo untyped string
         ExportedTwo untyped string

我想要做的是获取ExportedOne

英文:

I am trying to add some simple validation code for some exported types in a package full of constants. I want to walk the package, figure out the exported consts (which are just strings) and verify their format.

Think of it like I have a flags package that exports consts FlagDoAThing = "do-a-thing". I want to walk that package and check out what those values are.


As an example I've got two files:

// main.go
func main() {
	cfg := &packages.Config{
		Mode: packages.NeedTypes,
	}
	pkgs, _ := packages.Load(cfg, "package-inspector/other")
	pkg := pkgs[0]

	scope := pkg.Types.Scope()
	for _, name := range scope.Names() {
		fmt.Println(name)
		obj := scope.Lookup(name)
		fmt.Println(obj)
		fmt.Println("\t", obj.Id(), obj.Type())
	}
}

Then in my other package I have

package other

const (
	ExportedOne = "exported_one"
	ExportedTwo = "exported_two"

	privateOne = "private_one"
)

When running locally (couldn't get the playground to like me) I am seeing

go run main.go
ExportedOne
const package-inspector/other.ExportedOne untyped string
         ExportedOne untyped string
ExportedTwo
const package-inspector/other.ExportedTwo untyped string
         ExportedTwo untyped string

What I'm trying to do is get a handle on the value of ExportedOne.

答案1

得分: 1

你可以对对象进行类型断言,将其断言为*types.Const,然后通过其Val方法访问该值。

o := s.Lookup(name)
if c, ok := o.(*types.Const); ok {
    fmt.Println(c.Val())
}

示例见:https://go.dev/play/p/oXX7Mo897bk

英文:

You can type-assert the object to *types.Const and then access the value through its Val method.

o := s.Lookup(name)
if c, ok := o.(*types.Const); ok {
    fmt.Println(c.Val())
}

See example: https://go.dev/play/p/oXX7Mo897bk

huangapple
  • 本文由 发表于 2022年8月5日 08:30:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/73243484.html
匿名

发表评论

匿名网友

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

确定