Builder pattern generator for Go structs with compile-time safety.
go install github.com/slavaavr/go-struct-builder/cmd/gosb@latest- To generate a struct builder, add the appropriate
go:generatecomment:
// input.go - a file where the struct is located
//go:generate gosb -source=input.go
type A struct {
F1 int
F2 string
}Then run the command:
go generate ./...That’s it! After this, it will be possible to create the struct like this:
NewABuilder().WithF1(42).WithF2("hello").Build()- CLI
//go:generate gosb -source=input.go
//go:generate gosb -source=input.go -features=ptr,arr,opt
- Possible use cases can be found in this folder.
- There are two types of struct fields:
requiredandoptional. - By default, every
pointerfield (as well as theOptiontype from thegithub.com/samber/mopackage) isoptional, and all other fields arerequired. - To change the default behavior, use the appropriate struct tags:
//go:generate gosb -source=input.go
type B struct {
F1 *int `gosb:"required"` // pointer field overridden to required
F2 string `gosb:"optional"` // non-pointer field overridden to optional
}The generated builder ensures that required fields are provided.
- For a
privatestruct, aprivatebuilder will be generated. - If struct has
privatefields, along with the buildergetter methodswill be generated. - Supports
genericsandembedded structs.
-source(required): A file containing a struct to generate a builder for.-features(optional): A comma-separated list of features:ptr: Generates an additional method for each pointer field that accepts a non-pointer argument.
// Field: F1 *string b.WithF1(&s) // always available b.WithF1Value("hello") // added by `ptr`
arr: Generates an additional method for each array field using varargs.
// Field: F1 []string b.WithF1([]string{"a", "b"}) // always available b.WithF1Value("a", "b") // added by `arr`
opt: Generates an additional method for eachOptionfield (from thegithub.com/samber/molibrary), unwrapping theOptiontype and setting the value directly.
// Field: F1 mo.Option[int] b.WithF1(mo.Some(42)) // always available b.WithF1Value(42) // added by `opt`