Go - Options Pattern
In go, it’s really useful pattern to pass options to functions. It’s a common usecase to have optional arguments to a function. I use it mostly to initialize something with default values and optionally override them. Primary idea is to use variadic arguments to pass options to a function. eg: func NewService(options ...ServiceOption) *Service { ... } options ...ServiceOption is the variadic argument. There are two ways to do this. Using a struct with all the options as a field. Using functions with each option value as an argument. Using a struct to pass options Example usage package main type ServiceConfig struct { Color string Size int Type string } func main() { // Initialize with default values s := NewService() // Override some of the default values s = NewService(&ServiceConfig{ Color: "red", Size: 10, }) } How to setup this options pattern You can use config... to accept any number of args in a function. Let’s create a config section with init config function. ...