Practical Go: Functional Options Pattern
January 20, 2023
Go by default not support set default and optional argument in a function. The simple approach is using variadic argument but only support 1 data type for example func createSomething(input1, input2variadic...string)
To supporting multiple type argument in a function you can use functional options pattern, basically variadic argument with type function. The goals is like code example below
Using functional options pattern you can select the necessary options only, even without argument (server.New()
) the struct creation is valid.
The main problem, if the struct is big we must implement all optional function. Fortunately I already build simple tools for generate optional function.
Install on your system using command go install github.com/lumochift/optgen@latest
.
Let's expand Server
struct above with additional config timeout
and maxConn
.
Then generate functional options implementation using command optgen -file server.go -name Server -w
. Don't forget use -w
to append implementation to the selected file server.go
. The result only generate function SetHost
and SetPort
only because declared opt
in the struct tag just for host
and port
.
To generate all fields as optional parameter use flag -all
for example optgen -file server.go -name Server -w -all
, previous generated code must be deleted manually 1
Footnotes
-
The limitation
optgen
CLI only append code, not replace previously generated code. ↩