Go Generics: Use Structs for Generic Arguments Lists - Evan Moses

submited by
Style Pass
2024-04-30 22:00:08

I have a preference for functional-style programming. I tend to model algorithms in my head as data and transforms of that data (versus, say, objects with behaviors). When I see a pattern repeat itself in my code my first instinct is to reach for a higher-order function to abstract that pattern.

However, my day job is coding in Go. I have mixed feelings about the language and I’m not gonna start a Go flame war here, but I don’t think it’s controversial to say that Go does not lend itself to functional patterns.

I implemented a new, faster algorithm with to make some security calculations for our system; the details are unimportant, but if the result differed between the old code and my new algorithm, it would represent a serious problem for our customers. To make sure my new algorithm worked correctly, my plan was to calculate it the new way and the old way, compare the two values, and return the old value, logging an error if there were differences. I added two feature flags: UseNewAlgorithmDark enabled the new calculation with comparison and logging, and UseNewAlgorithmOnly stopped using the old calculation and just returned the result of the new one.

There are actually a few different places in the code that would be using the new code, and they did different calculations with it. So I now had multiple places in code that looked something like this:

Leave a Comment