DEV Community

Lewis Reay
Lewis Reay

Posted on

Creating a hash map based on the non zero values within a struct in Go

#go

I recently had a requirement to generate SQL queries based on the non zero values within a known struct.

It's common to duplicate structs to separates areas of your code (e.g your database struct may use types from the sql package, web struct may use pointers to avoid the zero value. We wouldn't want our 'core' struct to know about this). This works well for a lot of use cases, but gets unwieldy quickly.

This could also be done via reflect. Reflect is often avoided, and for good reason! It could be a foot gun if not used correctly as it panics on most errors and sometimes has questionable performance.

I have written partial which returns the non zero values in a struct, based on the field tag. The field tag is required, and supplying an unknown tag will return an empty map. This functionality exists due to me wanting to select fields that only have the 'db' tag and may become optional in the future.

Top comments (0)