0
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?

GOのiotaについて

Posted at

はじめに

GOのプロジェクトであまり見たことのない書き方を発見し、ちょっと混乱したのでまとめてみることにしました。

iotaとは?

constでまとめて定数を定義する際に自動で連番を定義することができる識別子です、また生成される連番と式を組み合わせて使用することも出来るため、簡単に柔軟な定数定義が可能です

基本的な使い方

iotaを使用しない場合

package main

import "fmt"

const (
	zero  = 0
	one   = 1
	two   = 2
	three = 3
)

func main() {
	fmt.Println(zero)
	fmt.Println(one)
	fmt.Println(two)
	fmt.Println(three)
}

出力結果

0
1
2
3

iotaを使用した場合

package main

import "fmt"

const (
	zero = iota
	one
	two
	three
)

func main() {
	fmt.Println(zero)
	fmt.Println(one)
	fmt.Println(two)
	fmt.Println(three)
}

出力結果

0
1
2
3

このように全く同じ連番を簡単に記載することが可能で、新しい定数を追加したい場合は末尾に追加するだけで定数定義が完了します

式と組み合わせて使用する場合

const (
	zero = iota * iota
	one
	two
	three
)
0
1
4
9

このように式と組み合わせることにより、連番以外の生成も可能です

const (
	zero = iota + 1
	one
	two
	three
)
1
2
3
4

プログラムの関係上「0」を使用したくない場合、+1から始めることで1スタートの連番を生成できます

連番を生成する範囲

連番が生成される範囲は、ConstSpec(constの括弧の中)でインクリメントされます

package main

import "fmt"

const (
	zero  = 0
	one   = 1
	two   = 2
	three = 3
)

const (
	zero_2  = 0
	one_2   = 1
	two_2   = 2
	three_2 = 3
)
0
1
2
3
0
1
2
3
0
0
0

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
0
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?