SoFunction
Updated on 2025-03-05

Go develops go-optioner tool to easily generate function option mode code

Preface

Recently, when I was doing refactoring code, I had a problem: when using function option mode to construct a struct, I needed to manually write a lot of code to set options functions due to too many fields in that struct. Such work is both tedious and prone to errors.

To solve this problem, I startedgithubThe above is looking for tools that can automatically generate function option mode code based on the definition of the structure. Although I found several related tools, they did not fully meet my requirements. So I decided to do it myself and developed itgo-optionerTools and recommend them to everyone.

go-optioner

go-optionerIt's one inGoA tool in the code to generate function option mode code. This tool can automatically generate corresponding option codes based on the given structure definition.

Install

1、go install /chenmingyong0423/go-optioner/cmd/optioner@latest

2. ExecutionoptionerCommand check whether the installation is successful

> 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

If you have successfully installed it, but the promptoptionerThe command cannot be found, please confirm whether it has been selected.$GOPATH/binAdd to environment variables.

Usage tutorial

You can use it directlyoptionerCommand generates the corresponding structurefunctional optionsCode, can also be usedgo generateCommands are generated in batches.

option command

1. First, you need to create a structure containing the code that needs to generate function option patternGodocument. In the structure field, you can useoptTags to control whether it isNewXXX()Required parameters of the function and generate corresponding functions.

package example
type User struct {
    Name   string`opt:"-"`
    Age    int
    Gender string
}

If the field is definedoptTag, and the value is-, then it will beNewXXXRequired parameters of the function and will not generate the fieldWithXXXFunction.

Note: Must declarepackage

2. Execute in the file directory containing the structure definitionoptioner -type XXXCommand, of whichXXXis the name of the structure. After executing the command,optionerThe tool will generate the corresponding function option mode code based on the structure definition. The content is as follows:

// Generated by optioner -type User; DO NOT EDIT
// If you have any questions, please create issues and submit contributions at:
// /chenmingyong0423/go-optioner
package example
type UserOption func(*User)
func NewUser(name string, opts ...UserOption) *User {
    user := &User{
        Name: name,
    }
    for _, opt := range opts {
        opt(user)
    }
    return user
}
func WithAge(age int) UserOption {
    returnfunc(user *User) {
         = age
    }
}
func WithGender(gender string) UserOption {
    returnfunc(user *User) {
         = gender
    }
}

optionerThe tool will generate a name calledopt_xxx_gen.gofile, of whichxxxis the name of the structure, for exampleopt_user_gen.go. This file contains the generated function option code to initialize the structure and set the value of the structure field.

go generate command

Please note that in executiongo generateBefore command, make sure your project has been initializedGo ModulesOr correctly setGOPATH, and your project structure meetsGo ModulesorGOPATHRequirements.

1. First, you need to create a structure containing the code that needs to generate function option patternGodocument. On top of the structure definition, you need to add//go:generate optioner -type XXXcomments, among whichXXXis the name of the structure. This way the tool can generate corresponding code based on parameters. In the structure field, you can useoptTags to control whether it isNewXXX()Required parameters of the function and generate corresponding functions.

package example
//go:generate optioner -type User
type User struct {
    Name   string`opt:"-"`
    Age    int
    Gender string
}

If the field is definedoptTag, and the value is-, then it will beNewXXXRequired parameters of the function and will not generate the fieldWithXXXFunction.

Note: Must declarepackage

2. Execute in the file directory containing the structure definitiongo generatecommand, this will calloptionerThe tool generates the corresponding function option mode code based on the structure definition. The content is as follows:

// Generated by optioner -type User; DO NOT EDIT
// If you have any questions, please create issues and submit contributions at:
// /chenmingyong0423/go-optioner
package example
type UserOption func(*User)
func NewUser(name string, opts ...UserOption) *User {
    user := &User{
        Name: name,
    }
    for _, opt := range opts {
        opt(user)
    }
    return user
}
func WithAge(age int) UserOption {
    returnfunc(user *User) {
         = age
    }
}
func WithGender(gender string) UserOption {
    returnfunc(user *User) {
         = gender
    }
}

optionerThe tool will generate a name calledopt_xxx_gen.gofile, of whichxxxis the name of the structure, for exampleopt_user_gen.go. This file contains the generated function option code to initialize the structure and set the value of the structure field.

summary

In this article, I've introducedgo-opionerThe installation and use of open source tools can automatically generate code for function option modes based on the definition of the structure. It allows us to say goodbye to the tedious constructor writing and modification, making the code writing process more efficient and pleasant.

This is the article about Go developing go-optioner tools to easily generate function option mode code. For more related Go go-optioner content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!