A Tour of Go をやる! – その16 「Constants」 変えられねぇよ? 【Go言語/A Tour of Go】

サムネイル_Constants IT
記事ヘッダー_Constants

「A Tour of Go をやる!」シリーズの第16回目。
呆れるほど変数のお題が続いてますが、今回も期待通りの変数…いや定数?

- PR -

今回進めるページ「Constants」

今回進める「A Tour of Go」のページはこちら。

A Tour of Go

タイトルの「Constants」とは?

「忠実な」とか「定期的な」などの意味もあるようですが、「不変の」が近いニュアンス。
Go言語で 値が変わらない「不変の」変数 、つまり定数の使い方がお題です。

言語仕様の確認

それじゃ言語仕様。
今回関係しそうな「Constants」の説明と定義について引用しています。

There are boolean constants, rune constants, integer constants, floating-point constants, complex constants, and string constants. Rune, integer, floating-point, and complex constants are collectively called numeric constants.

ブール定数、ルーン定数、整数定数、浮動小数点定数、複素定数、および文字列定数があります。ルーン、整数、浮動小数点、および複素定数は、まとめて数値定数と呼ばれます。(by Google Translated.)

The Go Programming Language Specification - The Go Programming Language

A constant declaration binds a list of identifiers (the names of the constants) to the values of a list of constant expressions. The number of identifiers must be equal to the number of expressions, and the nth identifier on the left is bound to the value of the nth expression on the right.

定数宣言は、識別子のリスト(定数の名前)を定数式のリストの値にバインドします。識別子の数は式の数と同じである必要があり、左側のn番目の識別子は右側のn番目の式の値にバインドされます。(by Google Translated.)

The Go Programming Language Specification - The Go Programming Language
Go
ConstDecl      = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
ConstSpec      = IdentifierList [ [ Type ] "=" ExpressionList ] .

IdentifierList = identifier { "," identifier } .
ExpressionList = Expression { "," Expression } .
Expand

定数として扱える値の種類

「A Tour of Go」で説明されていますが、ざっくり4種類の値が定数として扱えるようです。

  • 文字型
  • 文字列型
  • ブール型
  • 数値型

定数宣言の書き方

定数の宣言は「const」キーワードから書き始めるようです。書き方は「const」が付く以外、変数宣言と似たような感じ。

Go
// 定数宣言の書き方
const [変数名] [型] = [値]  // 型を指定すれば指定した型
const [変数名] = [値]       // 型指定がなければ[値]に即した型

// e.g.
const wish = "大きなイチ○ツをくださいませ。"  // string型になる
const size_mm int = 150                    // int型
Expand

定数の中身は変更できない

まぁ定数ですもの…

Go
package main

import "fmt"

const wish = "大きなイチ○ツをくださいませんか?"
const size_mm int = 150

func main() {

  size_mm = 180

  fmt.Printf("%dmm程の%s", size_mm, wish)

}
Expand

Go Playground

:= は使えない

ダメです!使えません!

Go
package main

import "fmt"


func main() {

  const wish := "大きなイチ○ツをくださいませんか?"
  const size_mm int = 150

  fmt.Printf("%dmm程の%s", size_mm, wish)

}
Expand

Go Playground

サンプルプログラムを見てみる。

ほいでは「Constants」のサンプルプログラム。
お題に関係する箇所にはコメント打ってます。

Go
package main

import "fmt"

const Pi = 3.14

func main() {

  // 定数宣言、文字列なのでstring型となる
  const World = "世界"

  fmt.Println("Hello", World)
  fmt.Println("Happy", Pi, "Day")

  // 定数宣言、真偽値なのでbool型になる
  const Truth = true

  fmt.Println("Go rules?", Truth)

}
Expand

Go Playground

サンプルプログラムの中身は、定数を宣言して内容を出力するだけのプログラム。

さいごに

はい、ということで「Constants」のページは以上で終わり。
内容的には定数の基礎中の基礎な内容でしたし、特に難しいところはなかった感じです。
変数や定数の考え方は他のプログラミング言語でも共通なので、どこかでしっかり頭に入れておくと後々の為になりそうです。

と言った感じで、また次回~٩( ‘ω’ )و

コメント

タイトルとURLをコピーしました