Graceful Options Parameters in Golang

Frank Chung
Jul 10, 2020 · 1 min read
Let’s build options for your Golang function.

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:

  1. Can know whether an option is given or not.
  2. Disallow caller to set the option with invalid values.
  3. Option shall contain multiple configurable fields.
  4. 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!

DeepQ Research Engineering Blog

Technical sharing by HTC research engineering team.