The Go *Options pattern

Introduction Hello everyone! ๐Ÿ‘‹ In this article Iโ€™ll present you the options pattern in Golang. The pattern is useful when you want to create a function that takes different parameters as an option. Code Study: Building a rocket The following code defines a Rocket struct with 3 fields and a NewRocket function which builds an instance of the Rocket. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // Rocket models a rocket. type Rocket struct { name string nose Nose fuelCapacity int } // NewRocket returns a new rocket instance. func NewRocket(name string, nose Nose, fuelCapacity int) Rocket { return Rocket{ name: name, nose: nose, fuelCapacity: fuelCapacity, } } To use the NewRocket function one would have to write something like this: ...

November 26, 2024 ยท 4 min ยท Denis Nutiu