LoginSignup
7
10

More than 5 years have passed since last update.

ひさしぶりのHello world ~ Go編 ~

Last updated at Posted at 2015-12-02

「Hello world」を出力するコードを書くのは何年ぶりだろうか。こんなしょうもない記事を書くのはどうかと思うが、テンションが上がったので、書いてしまった。

下準備

Goのインストール

下記のページから適切なソースをダウンロードする。
https://golang.org/dl/

$ wget https://storage.googleapis.com/golang/go1.5.1.linux-amd64.tar.gz
$ tar xvzf go1.5.1.linux-amd64.tar.gz

.bashrc等に環境変数を設定する。PATHは適宜、ソースを解凍した場所に変えてください。

.bashrc
export GOROOT=$HOME/go
export GOPATH=$GOROOT/packages
export PATH=$PATH:$GOROOT/bin

.bashrcを読み込む

$ source .bashrc

これでインストール完了です。goコマンドが使えるようになると思います。

$ go
Go is a tool for managing Go source code.

Usage:

        go command [arguments]

The commands are:

        build       compile packages and dependencies
        clean       remove object files
        doc         show documentation for package or symbol
        env         print Go environment information
        fix         run go tool fix on packages
        fmt         run gofmt on 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
        run         compile and run Go program
        test        test packages
        tool        run specified go tool
        version     print Go version
        vet         run go tool vet on packages

Use "go help [command]" for more information about a command.

Additional help topics:

        c           calling between Go and C
        buildmode   description of build modes
        filetype    file types
        gopath      GOPATH environment variable
        environment environment variables
        importpath  import path syntax
        packages    description of package lists
        testflag    description of testing flags
        testfunc    description of testing functions

Use "go help [topic]" for more information about that topic.

Hello world

hello.goを作成して、下記のように編集します。

hello.go
package main

import "fmt"

func main() {
  fmt.Printf("Hello world\n")
}

fmtは、標準出力、標準入力が実装されているパッケージです。そのため、importする必要があります。
package mainはなんとなく意味はわかるんですが、簡単に調べた結果、

The first statement in a Go source file must be
package name

とか

Executable commands must always use package main.

しか書かれていたので、main関数をパッケージ化してくれるんだろうwぐらいの認識です。

最後にコンパイルと実行

$ go run hello.go
Hello world

runコマンドはコンパイルと実行してくれるコマンドです。
下記のようにすると、コンパイルして実行ファイルを作成、実行もできます。

$ go build hello.go
$ ls 
hello hello.go
$ ./hello
Hello world

参考

あとがき

こういう記事は、普及する前に書きたいね。

7
10
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
7
10