Discoverable functional options pattern

Hello. Today’s will be a quick post. Everyone knows and loves/hates functional options1 in Go. The biggest gripe people get with it is, that the options aren’t discoverable and that there is no IDE support for nicely auto-completing options. My thought about this was that, what if we would just hang it on a struct? Let’s see how that looks. Consider this normal server builder with options: type Server struct { Name string Address string Port int } func WithName(name string) ServerOptFn { return func(s *Server) { s.Name = name } } func WithAddress(address string) ServerOptFn { return func(s *Server) { s.Address = address } } func WithPort(port int) ServerOptFn { return func(s *Server) { s.Port = port } } type ServerOptFn func(*Server) func NewServer(opts ...ServerOptFn) *Server { s := &Server{} for _, o := range opts { o(s) } return s } Now, what if you would like to retain the niceness of the clean options pattern where you don’t have to specify and empty struct but still could use a struct to gather the options together? ...

July 1, 2024 · 2 min · hannibal