前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >go optioner:轻松生成函数选项模式代码

go optioner:轻松生成函数选项模式代码

原创
作者头像
陈明勇
发布2024-12-13 22:52:19
发布2024-12-13 22:52:19
631
举报
文章被收录于专栏:Go 技术Go 技术Go技术干货

前言

之前写过一篇文章 —— [Go开源工具] go-optioner:轻松生成函数选项模式代码,详细讲解了 go optioner 工具的使用方法。不过,随着工具的不断更新,那篇文章中的内容已经和现在的实际用法有些出入了。所以,这次就重新写一篇,把最新的用法分享给大家。

准备好了吗?准备一杯你最喜欢的咖啡或茶,随着本文一探究竟吧。

go optioner

go-optioner 是一个在 Go 代码中生成函数选项模式代码的工具。该工具可以根据给定的结构定义自动生成相应的选项代码。

安装

  • 1、go install github.com/chenmingyong0423/go-optioner/cmd/optioner@latest
  • 2、执行 optioner 命令检查是否安装成功
代码语言:bash
复制
$ optioner
optioner is a tool for generating functional options pattern.
Usage:
         optioner [flags]
Flags:
         -type <struct name>
         -output <output path>, default: srcDir/opt_xxx_gen.go
         -with_prefix <the prefix of the With{filed_name} function>, default is With{filed_name}.If specified, such as User, it will generate WithUser{filed_name}
         -mode <the file writing mode>, default: write
         there are two available modes:
                 - write(Write/Overwrite): Overwrites or creates a new file.
                 - append (Append): Adds to the end of the file.

如果你安装成功了,但是提示 optioner 命令找不到,请确认是否已将 $GOPATH/bin 添加到环境变量中。

参数

使用 optioner 工具时,你可以通过以下参数定制其行为:

  • -type: 指定目标结构体的名称,这是一个必需参数。
  • -output: 设置生成代码的输出文件路径。这是一个可选参数,默认生成的文件名格式为 opt_{StructName}_gen.go,其中 {StructName} 是结构体的名称,文件位于当前目录下。
  • -with_prefix:设置 With{filed_name} 函数的前缀。这是一个可选参数,默认值为 With{filed_name}。如果指定了前缀,例如 User,则生成的函数名将变为 WithUser{filed_name}
  • -mode: 定义文件写入方式,接受的值有:
    • write(写入/覆盖):如果文件已存在,将其覆盖;如果文件不存在,创建新文件。
    • append(追加):将内容追加到现有文件的末尾。

使用教程

你可以直接使用 optioner 命令生成对应结构体的 functional options 代码,也可以使用 go generate 进行批量生成。

optioner 命令

  • 1、首先,假定您已经准备好一个 Go 文件,其中包含了您希望生成函数选项模式代码的结构体。在该结构体的字段上,您可以利用 opt 标签来标记哪些字段应作为 New{FieldName} 函数的必要参数。
代码语言:go
复制
package example

type User[T any, R any] struct {
    Name            string `opt:"-"`
    NecGenericFiled T      `opt:"-"`
    Age             int
    Gender          string
    GenericFiled    R
}

如果结构体字段使用了 opt 标签并将其值设置为 -,则该字段成为 New{FieldName} 函数的必需参数,同时不会为该字段生成 With{FieldName} 函数。

注意:必须声明 package

  • 2、在包含结构体定义的文件所在目录下,执行 optioner -type {StructName} 命令,将 {StructName} 替换为实际的结构体名称,例如 optioner -type User。此命令执行后,optioner 工具会根据结构体定义自动创建默认的 opt_user_gen.go 文件,并在其中生成函数选项模式代码。生成的代码结构如下所示:
代码语言:go
复制
// Generated by [optioner] command-line tool; DO NOT EDIT
// If you have any questions, please create issues and submit contributions at:
// https://github.com/chenmingyong0423/go-optioner

package example

type UserOption[T any, R any] func(*User[T, R])

func NewUser[T any, R any](name string, necGenericFiled T, opts ...UserOption[T, R]) *User[T, R] {
    user := &User[T, R]{
        Name:            name,
        NecGenericFiled: necGenericFiled,
    }

    for _, opt := range opts {
        opt(user)
    }

    return user
}

func WithAge[T any, R any](age int) UserOption[T, R] {
    return func(user *User[T, R]) {
        user.Age = age
    }
}

func WithGender[T any, R any](gender string) UserOption[T, R] {
    return func(user *User[T, R]) {
        user.Gender = gender
    }
}

func WithGenericFiled[T any, R any](genericFiled R) UserOption[T, R] {
    return func(user *User[T, R]) {
        user.GenericFiled = genericFiled
    }
}

如果需要自定义生成代码的输出文件路径,可以通过指定 outputmode 参数进行配置。

go generate 命令

请注意,在执行 go generate 命令之前,确保您的项目已经初始化 Go Modules 或正确设置了 GOPATH,并且您的项目结构符合 Go ModulesGOPATH 的要求。

  • 1、首先,假定您已经准备好一个 Go 文件,其中包含了您希望生成函数选项模式代码的结构体。在该结构体定义之上,添加注释 //go:generate optioner -type {StructName},并把 {StructName} 替换为您的实际结构体名称。例如,使用 //go:generate optioner -type User 来为 User 结构体生成代码。在该结构体的字段上,您可以利用 opt 标签来标记哪些字段应作为 New{FieldName} 函数的必要参数。
代码语言:go
复制
package example

//go:generate optioner -type User
type User[T any, R any] struct {
    Name            string `opt:"-"`
    NecGenericFiled T      `opt:"-"`
    Age             int
    Gender          string
    GenericFiled    R
}

如果结构体字段使用了 opt 标签并将其值设置为 -,则该字段成为 New{FieldName} 函数的必需参数,同时不会为该字段生成 With{FieldName} 函数。

注意:必须声明 package

  • 2、在包含结构体定义的文件所在目录下,运行 go generate 命令,这个命令将触发 optioner 工具,并根据结构体定义自动创建默认的 opt_user_gen.go 文件,同时在该文件中生成函数选项模式的代码。生成的代码结构如下所示:
代码语言:go
复制
// Generated by [optioner] command-line tool; DO NOT EDIT
// If you have any questions, please create issues and submit contributions at:
// https://github.com/chenmingyong0423/go-optioner

package example

type UserOption[T any, R any] func(*User[T, R])

func NewUser[T any, R any](name string, necGenericFiled T, opts ...UserOption[T, R]) *User[T, R] {
    user := &User[T, R]{
        Name:            name,
        NecGenericFiled: necGenericFiled,
    }

    for _, opt := range opts {
        opt(user)
    }

    return user
}

func WithAge[T any, R any](age int) UserOption[T, R] {
    return func(user *User[T, R]) {
        user.Age = age
    }
}

func WithGender[T any, R any](gender string) UserOption[T, R] {
    return func(user *User[T, R]) {
        user.Gender = gender
    }
}

func WithGenericFiled[T any, R any](genericFiled R) UserOption[T, R] {
    return func(user *User[T, R]) {
        user.GenericFiled = genericFiled
    }
}

如果需要自定义生成代码的输出文件路径,可以修改 //go:generate optioner -type User 的内容,通过指定 outputmode 参数进行配置。

小结

本文详细介绍了 go opioner 开源工具的安装和使用,它能够根据结构体的定义,自动生成函数选项模式的代码。它让我们告别繁琐的构造函数编写和修改,让代码编写过程更加高效和愉悦。

如果你有特别的建议和想法,欢迎提交 IssuesPull Request(PR),为 gooptioner` 工具提出宝贵的意见和贡献更好的功能和改进。

工具链:https://github.com/chenmingyong0423/go-optioner


你好,我是陈明勇,一名热爱技术、乐于分享的开发者,同时也是开源爱好者。

成功的路上并不拥挤,有没有兴趣结个伴?

关注我,加我好友,一起学习一起进步!

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • go optioner
  • 安装
  • 参数
  • 使用教程
    • optioner 命令
    • go generate 命令
  • 小结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档