Omitting constant expressions
July 13, 2023
Within a parenthesized
constdeclaration 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
iotaconstant generator this mechanism permits light-weight declaration of sequential values:
const ( Sunday = iota Monday Tuesday Wednesday Thursday Friday Partyday 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 two three ) fmt.Println(one, two, three)
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)
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
Duplicate map keys
It’s Monday again. That means I’ll be live-coding again! I hope you can join me. Composite literals … For map literals, all elements must have a key. It is an error to specify multiple elements with the same field name or constant key value. For non-constant map keys, see the section on evaluation order. I expect we can all agree this makes sense. Keys in a map literal must be unique.
I’ll be live coding again today! I hope you can join me! I’ll be continuing where I left off, working on a new feature for my open-source CouchDB SDK, https://kivik.io/. Join me to see how many mistakes a senior Go dev makes while coding. To kick off our dissection of expressions, we’ll look at the term “operand”. You may recall from your studies of algebra that an operand is the “object upon which an operator acts.
No live stream today. My office/recording studio is being painted. I’ll be back next week with more linter building! One last detail on iota… Iota … By definition, multiple uses of iota in the same ConstSpec all have the same value: const ( bit0, mask0 = 1 << iota, 1<<iota - 1 // bit0 == 1, mask0 == 0 (iota == 0) bit1, mask1 // bit1 == 2, mask1 == 1 (iota == 1) _, _ // (iota == 2, unused) bit3, mask3 // bit3 == 8, mask3 == 7 (iota == 3) ) This last example exploits the [implicit repetition](https://go.