Tips on Constants in Go
Explore how to utilize constants in Go programming with the iota identifier. Learn to create auto-incremented values, define custom types for compile-time checks, skip values, and use expressions for bitmasking. This lesson helps you write clearer, more maintainable Go code by mastering constant handling techniques.
We'll cover the following...
Iota: Elegant Constants
Some concepts have names, and sometimes we care about those names, even (or especially) in our code.
At other times, we only care to distinguish one thing from the other. There are times when there’s no inherently meaningful value for a thing. For example, if we’re storing products in a database table we probably don’t want to store their category as a string. We don’t care how the categories are named, and besides, marketing changes the names all the time.
We care only that they’re distinct from each other.
Instead of 0, 1, and 2 we could have chosen 17, 43, and 61. The values are arbitrary.
Constants are important but they can be hard to reason about and difficult to maintain. In some languages like Ruby developers often just avoid them. In Go, constants have many interesting subtleties that, when used ...