静的型付けプログラミング言語として急速に人気が向上しているGo言語(Golang)。
わたしも将来的に絶対使うことになるポジションにいますので、今のうちから勉強をはじめました笑
とりあえず、勉強始めということで、自分への備忘録も含め、
- Goのインストール
- 簡単な記述の解説
- ビルド、実行
- Hello World
まで紹介いたします。
Goのインストール
Goは上記のURLからインストール可能です。
各OSに合わせてダウンロード・インストールしてください。
インストールが完了したら、ターミナルで
1 |
go |
と入力してください。
【コマンドが見つかりません】
のようなエラーメッセージが出ずに、GoCLIに関する記述が表示されれば、Goが正常にインストールされている証拠です。(正常にインストールされていたら、以下のような結果が表示がされます。)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
Go is a tool for managing Go source code. Usage: go <command> [arguments] The commands are: bug start a bug report build compile packages and dependencies clean remove object files and cached files doc show documentation for package or symbol env print Go environment information fix update packages to use new APIs fmt gofmt (reformat) package sources generate generate Go files by processing source get download and install packages and dependencies install compile and install packages and dependencies list list packages or modules mod module maintenance run compile and run Go program test test packages tool run specified go tool version print Go version vet report likely mistakes in packages Use "go help <command>" for more information about a command. Additional help topics: buildmode build modes c calling between Go and C cache build and test caching environment environment variables filetype file types go.mod the go.mod file gopath GOPATH environment variable gopath-get legacy GOPATH go get goproxy module proxy protocol importpath import path syntax modules modules, module versions, and more module-get module-aware go get packages package lists and patterns testflag testing flags testfunc testing functions Use "go help <topic>" for more information about that topic. |
hello.goの作成
Hello Worldを表示するためにまずはgoを記述していくファイルを作成しましょう。
hello.goというファイルを作成し、そのファイルの中身を
1 2 3 4 5 6 7 |
package main import "fmt" func main() { fmt.Printf("Hello World!") } |
としてください。
上から順に記述の説明をすると、
1 |
package main |
mainというパッケージを宣言しています。
Goの場合、「main」というパッケージ名は特別で実行可能なファイルを作成するためのパッケージ名になります。
1 |
import "fmt" |
このimportという記述は、javascriptのrequireやimportと同じように、外部のパッケージをインポートして、hello.go内で使用できるようにするための記述です。
1 2 3 |
func main() { fmt.Printf("Hello World!") } |
最後の、func main() {} に関しては、他のプログラミング言語と全く同じように、mainという関数を作成しているだけです。
Goのビルド・実行
Go言語はPHPやperlなどのインタプリタ言語とは違い、コンパイル言語です。
ファイルの実行をする前に必ずコンパイルをして、実行可能な状態にしなければなりません。
今回作成したhello.goをビルドするには、hello.goがある位置で
1 |
go build hello.go |
とターミナルで実行してください。
コンパイルが完了すると、「hello」というファイルが作成されます。
そして、再度ターミナルで
1 |
./hello |
と実行すると、「Hello World!」と出力されることが確認できます。
これでGo言語のセットアップと実行は完了です!
web業界出身だとPHPやRuby、javascriptといったコンパイルの必要がないインタプリタ言語がメインなので、コンパイル言語かつ静的型付け言語のGoを敬遠しがちかもしれません。
しかし、一度触ってみるとすごく簡単にセットアップもビルド・実行もできて、ストレスフリーでプログラミングができそうな気がしています笑
これから、Goの情報をこのブログでドンドン発信していきますので、是非、遊びに来てくださいね!