duansha7453
duansha7453
2019-04-01 08:53

如何进行:从多个包中生成字符串常量?

  • generate
已采纳

I have a struct like this:

.foo/bar/constants.go
.foo/constants.go
.main.go 

In main.go I declare the type:

package agepack
type EventType uint
//go:generate stringer -type EventType
const (
    FirstType EventType iota
    SecondType
    ....
)

In each constants.go I have soimething like this:

package foo
const (
   OneMoreType agepack.EventType = 100 + iota
)

How can I generate stringer with values from all packages?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doudou8893 doudou8893 2年前

    golang.org/x/tools/cmd/stringer doesn't support this. Quoting from its doc:

    With no arguments, it processes the package in the current directory. Otherwise, the arguments must name a single directory holding a Go package or a set of Go source files that represent a single Go package.

    Easiest solution would be to put all enum values in the same package. You may use separate files, but they must be in the same package.

    If you want / must use multiple packages, you can only do this with stringer if you use different types, each defined in the package in which you list the constants.

    点赞 评论 复制链接分享