🛠 A lightweight and generic functional options helper for Go — clean, type-safe configuration without verbose constructors.
✅ Generic – works with any struct type
✅ Type-safe – powered by Go generics (Option[T any])
✅ Composable – combine multiple options into one
✅ Convenient – create new objects or modify existing ones easily
✅ Zero-dependency – no external packages required
go get github.com/pragus/options| Function | Signature | Description | Example |
|---|---|---|---|
Apply |
func Apply[T any](options ...Option[T]) T |
Creates a new object of type T and applies options to it. |
cfg := Apply(WithName("App"), WithPort(8080)) |
ApplyTo |
func ApplyTo[T any](cfg *T, options ...Option[T]) |
Applies options to an existing object. | ApplyTo(&cfg, WithDebug(true)) |
ApplyWithDefault |
func ApplyWithDefault[T any](def T, options ...Option[T]) T |
Applies options to a provided default value. | cfg := ApplyWithDefault(defaults, WithPort(443)) |
Combine |
func Combine[T any](options ...Option[T]) Option[T] |
Merges multiple options into a single Option[T]. |
common := Combine(WithPort(80), WithDebug(true)) |
Make |
func Make[T, V any](fn func(*T, V)) func(V) Option[T] |
Generates an Option[T] constructor from a setter function. |
WithName := Make(func(c *Config, v string) { c.Name = v }) |
package main
import (
"fmt"
"github.com/pragus/options"
)
type Config struct {
Name string
Port int
Debug bool
}
var (
WithName = options.Make(func(c *Config, v string) { c.Name = v })
WithPort = options.Make(func(c *Config, v int) { c.Port = v })
WithDebug = options.Make(func(c *Config, v bool) { c.Debug = v })
)
func main() {
cfg := options.Apply(
WithName("MyApp"),
WithPort(8080),
WithDebug(true),
)
fmt.Printf("%+v\n", cfg)
}{Name:MyApp Port:8080 Debug:true}
cfg := options.Apply(
WithName("Server"),
WithPort(443),
)cfg := &Config{Name: "default"}
options.ApplyTo(cfg, WithName("updated"))defaults := Config{Name: "default", Port: 80}
cfg := options.ApplyWithDefault(defaults, WithPort(8080))common := options.Combine(
WithPort(443),
WithDebug(true),
)
cfg := options.Apply(WithName("API"), common)package main
import (
"fmt"
"github.com/pragus/options"
)
type Config struct {
Name string
Port int
Debug bool
}
var (
WithName = options.Make(func(c *Config, v string) { c.Name = v })
WithPort = options.Make(func(c *Config, v int) { c.Port = v })
WithDebug = options.Make(func(c *Config, v bool) { c.Debug = v })
)
func main() {
defaults := Config{Name: "default", Port: 80, Debug: false}
// Create from defaults
cfg := options.ApplyWithDefault(
defaults,
WithName("ProductionServer"),
WithPort(443),
WithDebug(true),
)
fmt.Printf("Final config: %+v\n", cfg)
// Modify existing
existing := &Config{Name: "Staging"}
options.ApplyTo(existing, WithDebug(true))
fmt.Printf("Updated existing: %+v\n", existing)
// Combine multiple options into one
combined := options.Combine(
WithName("Combined"),
WithPort(9000),
)
fmt.Printf("From combined: %+v\n", options.Apply(combined))
}