
Go Bitwise Flags and Bitmasks: Configuration Pattern Guide
I was adding my eighth boolean toggle to a config struct — EnableCompression , SkipValidation , LogQueries , and so on. Eight fields, eight if cfg.Field checks, eight more lines in my YAML. The boilerplate was starting to annoy me. Then I replaced them with this: type ConfigFlags int const ( EnableCompression ConfigFlags = 1 << iota // 1 (0001) SkipValidation // 2 (0010) LogQueries // 4 (0100) // next one is 8 (1000), then 16 (00010000)... ) cfg := EnableCompression | LogQueries if cfg & ( EnableCompression | LogQueries ) != 0 { // do stuff } One integer. One check for any combination. Bitwise operators — OR ( | ) to combine, AND ( & ) to check, XOR ( ^ ) to toggle — handle the logic. And iota generates the bit positions automatically. What bit flags look like Each bit in a byte represents a separate option. An RGB color example: const ( Red = 0 b00000001 // bit 0 Green = 0 b00000010 // bit 1 Blue = 0 b00000100 // bit 2 ) Visually, each bit position controls one color: bit: 7 6 5 4 3 2
Continue reading on Dev.to
Opens in a new tab



