LoginSignup
0
0

【Go言語】定数の使い方

Posted at

変数や引数などに代入して利用する値のことを、まとめて定数と呼ぶ。
Go言語の定数の扱い方について、その特性と利用方法を説明する。

型のない定数の定義

Goでは、constキーワードで定数を定義できる。
実行時ではなく、コンパイル時に定数の値が計算されるため、実行時のコストは発生しない。

const (
    a = 1
    b = 1 + 2 // 演算も可能
    c = 9223372036854775807 + 1 // uint64を超える数値も可能
    d = "hello world" // 文字列定数
)

型付き定数の定義

型を指定して定数を定義することもできる。

type ErrorCode int

const (
    f int = 10
    code ErrorCode = 10
)

iotaについて

iota識別子を使用して連即した定数を簡単に作成することができる。

サンプル

const (
    Sunday = iota  // 0
    Monday         // 1
    Tuesday        // 2
    Wednesday      // 3
    Thursday       // 4
    Friday         // 5
    Saturday       // 6
)

iotaは式の一部としても使用できる

const (
    Bit0 = 1 << iota  // 1 << 0 == 1
    Bit1              // 1 << 1 == 2
    Bit2              // 1 << 2 == 4
    Bit3              // 1 << 3 == 8
)

constブロックを分けることでiotaの値をリセットすることができる

const (
    Apple = iota // 0
    Grape        // 1
    Orange       // 2
)

const (
    Cat = iota // 0 (新しいconstブロックでリセットされる)
    Dog        // 1
)

参考

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