Graceful Options Parameters in Golang
Published in
1 min readJul 10, 2020
Sometimes we provide a function with optional configurations to decorate it, how to write it in a graceful manner ?
To build a great options, there are several guidelines:
- Can know whether an option is given or not.
- Disallow caller to set the option with invalid values.
- Option shall contain multiple configurable fields.
- If no option is given, the function shall work normally.
Example 1:
The above example provides several static With helpers to generate an internal setting object. However, it is required to implement Apply function for each With helper.
Example 2:
This example apply a builder pattern for caller to build a desired option. No need to code a lots of type, instead need to write a merge function for the internal setting.
Welcome to feedback how you write graceful options in Golang and comments the example for me.
Thanks!