golang通过代码注释自动生成枚举类型插件库go-enum的使用

Golang通过代码注释自动生成枚举类型插件库go-enum的使用

go-enum是一个用于Golang的枚举生成器,它可以通过代码注释自动生成枚举类型和相关功能代码。

工作原理

go-enum会处理带有特殊注释的类型声明,并生成包含iota定义和各种可选功能的代码。

基本示例

// ENUM(jpeg, jpg, png, tiff, gif)
type ImageType int

运行go-enum后会生成:

const (
    // ImageTypeJpeg is a ImageType of type Jpeg.
    ImageTypeJpeg ImageType = iota
    // ImageTypeJpg is a ImageType of type Jpg.
    ImageTypeJpg
    // ImageTypePng is a ImageType of type Png.
    ImageTypePng
    // ImageTypeTiff is a ImageType of type Tiff.
    ImageTypeTiff
    // ImageTypeGif is a ImageType of type Gif.
    ImageTypeGif
)

// String implements the Stringer interface.
func (x ImageType) String() string

// ParseImageType attempts to convert a string to a ImageType.
func ParseImageType(name string) (ImageType, error)

// MarshalText implements the text marshaller method.
func (x ImageType) MarshalText() ([]byte, error)

// UnmarshalText implements the text unmarshaller method.
func (x *ImageType) UnmarshalText(text []byte) error

字符串类型枚举

go-enum也支持字符串类型的枚举:

// ENUM(pending, running, completed, failed)
type StrState string

生成结果:

const (
    // StrStatePending is a StrState of type pending.
    StrStatePending StrState = "pending"
    // StrStateRunning is a StrState of type running.
    StrStateRunning StrState = "running"
    // StrStateCompleted is a StrState of type completed.
    StrStateCompleted StrState = "completed"
    // StrStateFailed is a StrState of type failed.
    StrStateFailed StrState = "failed"
)

完整示例

下面是一个更完整的示例,展示如何定义和使用go-enum:

// Color is an enumeration of colors that are allowed.
/* ENUM(
Black, White, Red
Green = 33 // Green starts with 33
*/
// Blue
// grey=
// yellow
// blue-green
// red-orange
// yellow_green
// red-orange-blue
// )
type Color int32

生成的代码将包含:

const (
    // ColorBlack is a Color of type Black.
    ColorBlack Color = iota
    // ColorWhite is a Color of type White.
    ColorWhite
    // ColorRed is a Color of type Red.
    ColorRed
    // ColorGreen is a Color of type Green.
    // Green starts with 33
    ColorGreen Color = iota + 30
    // ColorBlue is a Color of type Blue.
    ColorBlue
    // ColorGrey is a Color of type Grey.
    ColorGrey
    // ColorYellow is a Color of type Yellow.
    ColorYellow
    // ColorBlueGreen is a Color of type Blue-Green.
    ColorBlueGreen
    // ColorRedOrange is a Color of type Red-Orange.
    ColorRedOrange
    // ColorYellowGreen is a Color of type Yellow_green.
    ColorYellowGreen
    // ColorRedOrangeBlue is a Color of type Red-Orange-Blue.
    ColorRedOrangeBlue
)

// ...其他生成的函数...

安装和使用

安装

可以通过以下方式安装:

curl -fsSL "https://github.com/abice/go-enum/releases/download/$(GO_ENUM_VERSION)/go-enum_$(uname -s)_$(uname -m)" -o go-enum

或者使用Docker:

docker run -w /app -v $(pwd):/app abice/go-enum:$(GO_ENUM_VERSION)

在项目中使用

  1. 在Go文件中添加生成指令:
//go:generate go-enum --marshal
  1. 运行生成命令:
go generate ./...

Makefile示例

也可以在Makefile中使用:

STANDARD_ENUMS = ./example/animal_enum.go \
 ./example/color_enum.go

NULLABLE_ENUMS = ./example/sql_enum.go

$(STANDARD_ENUMS): GO_ENUM_FLAGS=--nocase --marshal --names --ptr
$(NULLABLE_ENUMS): GO_ENUM_FLAGS=--nocase --marshal --names --sqlnullint --ptr

enums: $(STANDARD_ENUMS) $(NULLABLE_ENUMS)

%_enum.go: %.go $(GOENUM) Makefile
 $(GOENUM) -f $*.go $(GO_ENUM_FLAGS)

命令选项

go-enum提供了多种选项来自定义生成行为:

go-enum --help

NAME:
   go-enum - An enum generator for go

USAGE:
   go-enum [global options] [arguments...]

GLOBAL OPTIONS:
   --file value, -f value          The file(s) to generate enums.
   --noprefix                      Prevents the constants generated from having the Enum as a prefix.
   --lower                         Adds lowercase variants of the enum strings for lookup.
   --nocase                        Adds case insensitive parsing to the enumeration.
   --marshal                       Adds text (and inherently json) marshalling functions.
   --sql                           Adds SQL database scan and value functions.
   --sqlint                        Tells the generator that a string typed enum should be stored in sql as an integer value.
   --flag                          Adds golang flag functions.
   --prefix value                  Adds a prefix with a user one.
   --names                         Generates a 'Names() []string' function.
   --values                        Generates a 'Values() []{{ENUM}}' function.
   --nocamel                       Removes the snake_case to CamelCase name changing.
   --ptr                           Adds a pointer method to get a pointer from const values.
   --sqlnullint                    Adds a Null{{ENUM}} type for marshalling a nullable int value to sql.
   --sqlnullstr                    Adds a Null{{ENUM}} type for marshalling a nullable string value to sql.
   --template value, -t value      Additional template file(s) to generate enums.
   --alias value, -a value         Adds or replaces aliases for a non alphanumeric value.
   --mustparse                     Adds a Must version of the Parse that will panic on failure.
   --forcelower                    Forces a camel cased comment to generate lowercased names.
   --forceupper                    Forces a camel cased comment to generate uppercased names.
   --nocomments                    Removes auto generated comments.
   --buildtag value, -b value      Adds build tags to a generated enum file.
   --help, -h                      show help
   --version, -v                   print the version

通过go-enum,你可以轻松地为Golang项目生成类型安全的枚举,并附带各种实用功能,如字符串转换、JSON序列化等。


更多关于golang通过代码注释自动生成枚举类型插件库go-enum的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang通过代码注释自动生成枚举类型插件库go-enum的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


使用go-enum自动生成Golang枚举类型

go-enum是一个通过代码注释自动生成Golang枚举类型的工具,它可以简化枚举类型的创建过程,避免手动编写大量重复代码。

安装go-enum

首先需要安装go-enum工具:

go install github.com/abice/go-enum@latest

基本使用方法

1. 定义枚举类型

在你的Go代码中,通过注释定义一个枚举类型:

// 使用go:generate指令告诉go generate如何生成代码
//go:generate go-enum --marshal --sql --names

// ENUM(pending, processing, completed, failed)
type Status int

2. 生成枚举代码

运行以下命令生成枚举代码:

go generate ./...

主要特性

1. 字符串转换

go-enum会自动生成String()方法,实现fmt.Stringer接口:

var s Status = StatusProcessing
fmt.Println(s.String()) // 输出 "processing"

2. JSON编组支持

使用--marshal标志时,会生成JSON编组方法:

//go:generate go-enum --marshal

// ENUM(pending, processing, completed, failed)
type Status int

示例使用:

s := StatusProcessing
data, _ := json.Marshal(s) // 输出 "processing"

var s2 Status
json.Unmarshal([]byte(`"completed"`), &s2) // s2 = StatusCompleted

3. 数据库支持

使用--sql标志时,会生成数据库扫描和值方法:

//go:generate go-enum --sql

// ENUM(pending, processing, completed, failed)
type Status int

示例使用:

var s Status
db.QueryRow("SELECT status FROM orders WHERE id = ?", 1).Scan(&s)

4. 自定义枚举值名称

使用--names标志可以自定义枚举值的名称:

//go:generate go-enum --names

// ENUM(
//   pending    = 0
//   processing = 1
//   completed  = 2
//   failed     = 3
// )
type Status int

5. 前缀配置

可以使用--prefix去除枚举值的前缀:

//go:generate go-enum --prefix=Status

// ENUM(pending, processing, completed, failed)
type Status int

这样生成的常量将是Pending而不是StatusPending

高级用法

1. 自定义值

可以为枚举指定自定义值:

// ENUM(
//   red   = 1
//   green = 2
//   blue  = 4
// )
type Color int

2. 位标志

使用--flag标志创建位标志枚举:

//go:generate go-enum --flag

// ENUM(
//   read   = 1
//   write  = 2
//   exec   = 4
// )
type Permission int

3. 多文件生成

使用--file标志可以将生成的代码输出到单独的文件:

//go:generate go-enum --file=enum_gen.go

// ENUM(pending, processing, completed, failed)
type Status int

完整示例

//go:generate go-enum --marshal --sql --names --prefix=OrderStatus

// ENUM(
//   pending    = 0
//   processing = 1
//   shipped    = 2
//   delivered  = 3
//   cancelled  = 4
// )
type OrderStatus int

运行go generate后会生成包含以下功能的代码:

  • String()方法
  • JSON编组/解组方法
  • 数据库扫描/值方法
  • 常量定义Pending = 0, Processing = 1
  • 从字符串解析的方法ParseOrderStatus()

注意事项

  1. go-enum需要在项目目录下运行go generate命令
  2. 确保注释格式正确,特别是//go:generate// ENUM注释
  3. 生成的代码会在同一包中创建,确保目录结构正确

go-enum通过自动化枚举类型的创建过程,可以显著减少样板代码,提高开发效率,同时保证类型安全。

回到顶部