Tips on Constants in Go
Useful tips and tricks for programming in Go.
Iota: Elegant Constants
Some concepts have names, and sometimes we care about those names, even (or especially) in our code.
const (CCVisa = "Visa"CCMasterCard = "MasterCard"CCAmericanExpress = "American Express")
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.
const (CategoryBooks = 0CategoryHealth = 1CategoryClothing = 2)
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 ...