Omitting constant expressions

July 13, 2023

Constant declarations

Within a parenthesized const declaration list the expression list may be omitted from any but the first ConstSpec. Such an empty list is equivalent to the textual substitution of the first preceding non-empty expression list and its type if any. Omitting the list of expressions is therefore equivalent to repeating the previous list. The number of identifiers must be equal to the number of expressions in the previous list. Together with the iota constant generator this mechanism permits light-weight declaration of sequential values:

const (
	Sunday = iota
	numberOfDays  // this constant is not exported

We’ll talk about iota tomorrow. Today let’s focus on the rest of this paragraph.

So in short, the expression list may be omitted in a parenthesized constant declaration, in which case the expression list is in effect copied from the first in the group:

	const (
		one = 1
	fmt.Println(one, two, three)

Prints: 1 1 1

That’s not very useful by itself, of course.

We can also do multiple assignments this way:

	const (
		one, two, three = 1, 2, 3
		i, ii, iii
	fmt.Println(one, two, three, i, ii, iii)

Prints: 1 2 3 1 2 3

Perhaps marginally more useful?

Tomorrow we’ll see how to make this feature more useful.

Quotes from The Go Programming Language Specification Version of December 15, 2022

Share this