Skip to content

Latest commit

 

History

History
124 lines (87 loc) · 2.72 KB

File metadata and controls

124 lines (87 loc) · 2.72 KB

Iota

Problem 1

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 = 1b, c = 2, 3の部分のことをConstSpecと呼ぶようです。

const a = 1のように、ConstSpecを含む定数宣言全体はConstDecl(これがconstant declarationに相当)と定義されています。

次のように複数のConstSpecを並べたものも一つのConstDeclになります。

const (
    c = 3
    d = 4
)

Problem 2

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となります。