【Go】型付き定数 const
Go には enum がないため、ユーザ定義型の定数を const で並べて列挙値を表現する。
Go では const キーワードで定数を宣言できる。
単なる文字列や数値の定数ではなく、ユーザ定義型を指定することで「その型しか受け付けない」型安全な列挙を実現できる。
const ( … ) で複数の定数をグループ化できる
iota を使うと連番 (0, 1, 2 … ) を自動生成できる(文字列定数には使えない)
型を指定しない定数 (const x = "hello") は untyped constant となり、型安全性が弱まる
型を指定した定数 (const x ImagteFormat = "jpg") は、その型以外の変数に代入するとコンパイルエラーになる
コード例
type ImageFormat string // ImageFormat は画像形式を表す型
const (
FormatJPG ImageFormat = "jpg"
FormatPNG ImageFormat = "png"
FormatGIF ImageFormat = "gif"
)
// 型安全:ImageFormat を要求する関数に string を渡すことはできない
func SetFormat(f ImageFormat) {
fmt.Println("format:", f)
}
a
func main() {
SetFormat(FormatJPG) // OK
SetFromat("jpg") // NG: コンパイルエラー
}type Color int
const (
Red Color = iota // 0
Green // 1
Blue // 2
)