LoginSignup
0
0

More than 3 years have passed since last update.

const

Last updated at Posted at 2019-06-02

constは定数を宣言する。文字、文字列、boolean、数値のみが使える。:=を使うことはできない。
関数内にもかけるが普通はグローバルに。

書き方

const Pi = 3.1415

//複数の場合は
const (
    Username = "username"
    Password = "password"
)

Printlnで出力

const (
    Pi       = 3.1415
    Username = "username"
    Password = "password"
)

func main() {
    fmt.Println(Pi, Username, Password)
}

番外編

var long int = 9223372036854775807 + 1
func main() {
    fmt.Println(long - 1)
}

var long int = 9223372036854775807 + 1この時点でオーバーフローとなってエラー。ところが以下のコードはOK

const long = 9223372036854775807 + 1
func main() {
    fmt.Println(long - 1)
}

constは型を宣言しない。
Goのコンパイラに解釈はされてるけど実行されてない。だから最後の例では、fmt.Println(long-1)に代入されるまでconst long = 9223372036854775807 + 1は実行されてなくて、代入された時点で実行されるけど-1されるのでオーバーフローしない結果になる。
varではオーバーフローするものを定義した時点でエラー発生するが、constの場合は大丈夫ってことで。(あまり使われないけど一応)

【参考】
現役シリコンバレーエンジニアが教えるGo入門(https://www.udemy.com/share/100BhMB0obeFpbTX4=/)

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