package main
import (
"fmt"
)
const (
a = 1
b = 2
c = iota
)
const (
d = 2
e = iota
)
func main() {
fmt.Println(a*b*c*d*e)
}
ANSWER
- 8と表示される。
Within a constant declaration, the predeclared identifier iota represents successive untyped integer constants. Its value is the index of the respective ConstSpec in that constant declaration, starting at zero.
const宣言の中では、宣言済みの名前であるiota
は連続する型なしの整数のconstantを表します。その値は、対応するConstSpecの番号です。番号は0から始まります。
ConstSpecがわかりにくいですが、
ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
ConstSpec = IdentifierList [ [ Type ] "=" ExpressionList ] .
を見ると、
const a = 1
const b, c = 2, 3
のようなコードにおいて、a = 1
や b, c = 2, 3
の部分のことをConstSpec
と呼ぶようです。
const a = 1
のように、ConstSpec
を含む定数宣言全体はConstDecl
(これがconstant declarationに相当)と定義されています。
次のように複数のConstSpec
を並べたものも一つのConstDecl
になります。
const (
c = 3
d = 4
)
package main
import (
"fmt"
)
const (
a = 1
b, c = 1 << iota, 1 << iota
d = 1 << iota
e = 1 << iota
)
func main() {
fmt.Println(a * b * c * d * e)
}
ANSWER
- 128と表示される。
Within a constant declaration, the predeclared identifier iota represents successive untyped integer constants. Its value is the index of the respective ConstSpec in that constant declaration, starting at zero.
const宣言の中では、宣言済みの名前であるiota
は連続する型なしの整数のconstantを表します。その値は、対応するConstSpecの番号です。番号は0から始まります。
ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
ConstSpec = IdentifierList [ [ Type ] "=" ExpressionList ] .
問題のConstDecl
を見直してみると、次のように4つのConstSpec
からなっていることがわかります。
const (
a = 1 // iota = 0, a = 1
b, c = 1 << iota, 1 << iota // この行は1つのConstSpecであり、どちらのiotaも1となる。b == c == 2
d = 1 << iota // iota = 2, d = 4
e = 1 << iota // iota = 3, e = 8
)
よってa~e
の積は、1*2*2*4*8 = 128
となります。