Functional Options in Go: With Generic

Amir So
4 min readJun 20, 2022

In this story, we will know the Functional Options pattern and implement it simply, and at the end, we will learn how to apply Generic (Go +1.18) to this solution.

Introduction

Functional options are a method of implementing clean APIs in Go. You've probably seen this pattern if you have done some integrations with GCP SDK or gRPC.

As you can see above, we can configure the clients by using optional functions, and we don't have to use a separate function for different purposes. E.g.

Implementation

This pattern allows us to design a flexible set of APIs to help arbitrary configurations and initialization of a struct.

Let's assume we have a client struct and it has two configurable fields:

--

--

No responses yet