Skip to content

slavaavr/go-struct-builder

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

go-struct-builder

Builder pattern generator for Go structs with compile-time safety.

Build Status

Installation

Go 1.18+

go install github.com/slavaavr/go-struct-builder/cmd/gosb@latest

Quick start

  • To generate a struct builder, add the appropriate go:generate comment:
// 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()

Examples

  • 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.

Required / Optional fields

  • There are two types of struct fields: required and optional.
  • By default, every pointer field (as well as the Option type from the github.com/samber/mo package) is optional, and all other fields are required.
  • 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.

Notes

  • For a private struct, a private builder will be generated.
  • If struct has private fields, along with the builder getter methods will be generated.
  • Supports generics and embedded structs.

Flags

  • -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 each Option field (from the github.com/samber/mo library), unwrapping the Option type and setting the value directly.
    // Field: F1 mo.Option[int]
    b.WithF1(mo.Some(42)) // always available
    b.WithF1Value(42) // added by `opt`

About

Builder pattern generator for Go structs

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published