Constant declarations
July 10, 2023
I’m live streaming again! You’ll probably read this after the fact, but if not, come join me live, or catch the replay! I’ll be building a real-world linter from scratch, picking up from the tutorial I did 2 weeks ago.
If you’ve been reading me for a while, you’ll recall we’ve already talked about constants in Go. However, we’ve done it in a slightly more abstract sense; constant literals, and they’re types.
Here we’re finally to the discussion of declaring named constants:
Constant declarations
A constant declaration binds a list of identifiers (the names of the constants) to the values of a list of constant expressions. The number of identifiers must be equal to the number of expressions, and the _n_th identifier on the left is bound to the value of the nth expression on the right.
ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) . ConstSpec = IdentifierList [ [ Type ] "=" ExpressionList ] . IdentifierList = identifier { "," identifier } . ExpressionList = Expression { "," Expression } .
There’s more to be said, which we’ll cover in the coming day or two, but for now, let’s just look at some examples, so this isn’t entirely abstract:
const foo = 123 // A single, untyped numeric constant
const bar int = 234 // A numeric constant of type int
const a, b c = "a", "b", "c" // Three untyped string constants
// I'm sure you can figure these out...
const (
x = 789
y = "yup"
z bool = true
)
Quotes from The Go Programming Language Specification Version of December 15, 2022