optgen
Optional function generator from struct.
Limitation
- Flag
-w
currently cannot update generated code, only append code
Installation
go get github.com/lumochift/optgen
Usage
Usage of ./optgen:
-all
generate all fields
-file string
path file
-name string
struct name
-tag string
custom tag (default "opt")
-w enable write mode
- Generate file with default tags
opt
//thing.go
package foo
type Thing struct {
Field1 string `opt`
Field2 []*int `opt`
Field3 map[byte]float64
}
For example we have thing.go
and need to generate functional option for struct Thing
, only field with opt
will generated:
optgen -file thing.go -name Thing
Output:
// Option is a Thing configurator to be supplied to NewThing() function.
type Option func(*Thing)
// NewThing returns a new Thing.
func NewThing(options ...Option) (*Thing, error) {
// Prepare a Thing with default host.
thing := &Thing{}
// Apply options.
for _, option := range options {
option(thing)
}
// Do anything here
return thing, nil
}
// SetField1 sets the Field1
func SetField1(field1 string) Option {
return func(c *Thing) {
c.Field1 = field1
}
}
// SetField2 sets the Field2
func SetField2(field2 []*int) Option {
return func(c *Thing) {
c.Field2 = field2
}
}