...

/

Tips on Constants in Go

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.

Press + to interact
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.

Press + to interact
const (
CategoryBooks = 0
CategoryHealth = 1
CategoryClothing = 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 ...

Access this course and 1400+ top-rated courses and projects.