Defining constants in Go
We define a constant with the const
keyword:
1const CategoryAutobiography = "Autobiography"
We can group multiple constants between brackets:
1const (
2 CategoryAutobiography = "Autobiography"
3 CategoryLargePrintRomance = "Large Print Romance"
4 CategoryParticlePhysics = "Particle Physics"
5)
When the set of constants need to be of a certain type, we can specify the type for the first constant, and the rest will infer it automatically:
1type Category int
2
3const (
4
5 CategoryAutobiography Category = 0
6 CategoryLargePrintRomance = 1
7 CategoryParticlePhysics = 2
8)
Numeric constants are high-precision values.
An untyped constant takes the type needed by its context.
References
- John Arundel, For the Love of Go
- https://go.dev/tour/basics/16
Next -> iota-constant-in-go
#values #constants #define #variables #golang #sets #programming