In a typical day I run experiments that use data and algorithms that require adjusting parameters and running on multiple hosts. I want an elegant solution to set options in a Go package. I recently started to experiment with functional options [1,2] and found the approach clean and simple, especially when most options use default values. The issue, of course, was that I had to write boilerplate code which is not too bad but I'd rather not do it. Inspired by the stringer command, I decided to try "go generate" to generate boilerplate for functional options. The result can be found here:
For a package with:
package example
//go:generate optioner -type Exampletype Example struct {
N int
F funt(int)int
}
The package user only needs to do this:
ex := example.NewExample(example.N(22), example.F(myFunc))
Warning: I use the ast package for the first time over the weekend and I'm sure this can be done in a more elegant way! Also, this tool may not be necessary in many cases, for example,
Martin Bruse suggested a simpler solution using anonymous functions:
ex := example.NewExample("test", func(ex *Example) {
ex.N = 22
ex.F = myFunc
})
as far as I can tell this is a good solution for many use cases except when default values are required which will also require boilerplate.
what do you think? any other ideas?