概要
Tour of Go の - Constant についてのサンプル。
今回は定数について。特に気になる点はありませんね。
Goでは公開レベルの取り決めがとてもシンプルになっていて
- 先頭が大文字で始まっていたらpublic
- 先頭が大文字以外で始まっていたら パッケージプライベート
という形になっています。分かりやすくて好きです。
サンプル
package tutorial import "fmt" const ( // パブリックスコープな定数宣言 (先頭を大文字で開始) PublicScopeConstants = "helloworld" // パッケージレベルでの定数宣言 (先頭を小文字で開始) packageScopeConstants = "hello" ) // Constant は、 Tour of Go - Constant (https://tour.golang.org/basics/15) の サンプルです。 func Constant() error { // ------------------------------------------------------------ // Go言語では、定数は const キーワードを用いて宣言する // 定数は、文字、文字列、bool値,数値でのみ利用できる // 定数は、 := を使用して宣言はできない // ------------------------------------------------------------ const localScopeConstants = "world" // 当然ながら、定数に再代入は不可能 // (cannot assign to localScopeConstants) // localScopeConstants = "hoge" fmt.Println(PublicScopeConstants, packageScopeConstants, localScopeConstants) return nil }
try-golang/tutorial_gotour_08_constant.go at master · devlights/try-golang · GitHub
実行すると以下な感じ。
[Name] "tutorial_gotour_const" helloworld hello world
過去の記事については、以下のページからご参照下さい。
- いろいろ備忘録日記まとめ
サンプルコードは、以下の場所で公開しています。
- いろいろ備忘録日記サンプルソース置き場