2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[The Go Programming Language Specification] Iota

Last updated at Posted at 2019-12-02

Iota

Golangのspecificationの日本語訳と、ちょっとした遊びぐらいのコードを載せていく感じで進めようと思うので、
すでにGolangでコードを書いている人にはつまらないかもしれないです

また、間違っている部分があればぜひご指摘いただけると嬉しいです🙇‍♂️

想定する読者層

Iota

本記事は公式のドキュメントを参考にしています

Iotaは以下のような状況になるまで関数の実行を遅延します

  • 関数がreturnを返す時
  • goroutinがpanicになった時

iotaの宣言方法

iotaはconstによる変数宣言の中で使うことができます。iotaは0から始まる連続する型のない定数を表します。

const (
    c0 = iota // c0 = 0
    c1 = iota // c1 = 1
    c2 = iota // c2 = 2
)

ちなみにvarでは宣言することができません

package main

import (
	"fmt"
)

var (
	zero = iota
)

func main() {
	fmt.Println(zero)
}
undefined: iota

サンプルプログラム

通常

package main

import (
	"fmt"
)

const (
	zero = iota
)

func main() {
	fmt.Println(zero)
}
0

iotaよりも早くconst内で宣言されている変数がある場合

package main
import (
	"fmt"
)
const (
	hoge = 10
	zero = iota
)
func main() {
	fmt.Println(zero)
}
1

iotaの宣言の合間に別の変数を宣言した時

  • const内ではiotaはインクリメントされる
  • iotaは前の値からインクリメントされる
package main
import (
	"fmt"
)
const (
	zero = iota + 1
	one
	hoge = 10
	three = iota
)
func main() {
	fmt.Println(zero)
	fmt.Println(one)
	fmt.Println(hoge)
	fmt.Println(three)
}
1
2
10
3

constでiotaを分ける

  • iotaはconstで分けると0へと初期化される

package main
import (
	"fmt"
)
const (
	zero = iota + 1
	one
	hoge = 10
)
const (
	three = iota
)
func main() {
	fmt.Println(hoge)
	fmt.Println(zero)
	fmt.Println(one)
	fmt.Println(three)
}
10
1
2
0

おまけ

  • iotaは整数値だけではない
  • floatを設定してみた
package main

import (
	"fmt"
)

const (
	zero = iota
	one
	two
	three float64 = iota * 0.4
	four
	five
)

func main() {
	fmt.Println(zero) // iota = 0
	fmt.Println(one)  // iota = 1
	fmt.Println(two)  // iota = 2
	fmt.Println(three)// iota = 3 * 0.4
	fmt.Println(four) // iota = 4 * 0.4
	fmt.Println(five) // iota = 5 * 0.4
}
0
1
2
1.2
1.6
2

2
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?