LoginSignup
22
19

More than 5 years have passed since last update.

Go言語の作業ディレクトリをドキュメントに従って作り直してみた

Last updated at Posted at 2015-08-26

今までとりあえず.goファイルを作ってgo runしたりgo buildしたりしていたけど、How to write Go guideの"Code organization"を読んで改めて開発環境を作り直してみた。

とりあえず作業ディレクトリを決める

作業ディレクトリはひとまずどこでも良さそう。

Your workspace can be located wherever you like

今回は/usr/local/workdir/goで作る。

$ mkdir /usr/local/workdir
$ mkdir /usr/local/workdir/go

パスを通す

The GOPATH environment variable specifies the location of your workspace. It is likely the only environment variable you'll need to set when developing Go code.

なのと、

For convenience, add the workspace's bin subdirectory to your PATH:

だそうなので、作った作業ディレクトリにパスを通す。

$ vi ~/.bash_profile

以下を追記

export GOPATH=/usr/local/workdir/go
export PATH=$PATH:$GOPATH/bin

$ source ~/.bash_profile

所定のディレクトリを作る

Go code must be kept inside a workspace. A workspace is a directory hierarchy with three directories at its root:

 ・src contains Go source files organized into packages (one package per directory),
 ・pkg contains package objects, and
 ・bin contains executable commands.

なので、

$ cd $GOPATH
$ mkdir src pkg bin

で、

If you keep your code in a source repository somewhere, then you should use the root of that source repository as your base path.

ということなので、Githubを使っている僕の場合は

$ mkdir src/github.com
$ mkdir src/github.com/chooyan

とディレクトリを作って、その下にパッケージを作っていく。

改めてHello Worldしてみる

$ cd src/github.com/chooyan
$ mkdir hello ; cd hello
$ vi hello.go

以下のHelloWorldをコピペして保存

hello.go
package main

import "fmt"

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

ファイルができたら、

$ go install github.com/chooyan/hello

特に何も出力はされないが、

This command builds the hello command, producing an executable binary. It then installs that binary to the workspace's bin directory as hello (or, under Windows, hello.exe)

というわけで、binフォルダの中に実行ファイルが生成される。

ll $GOPATH/bin
total 3752
-rwxr-xr-x  1 chooyan  staff  1919504  8 26 22:47 hello

先ほどここにパスを通したので、

$ hello
Hello, world.

できたできた。

あとはここからライブラリのパッケージを作ったり、Githubにpush gitにコミットしたり、他の人がpushしたライブラリをとってきたり、テストコード書いたりといろいろ続くのだけど、それはまた次で。

ポイント

Go言語のディレクトリ構成は、Githubのようなオープンな場でソースコードを共有することに最適化されていることと、

The go tool is designed to work with open source code maintained in public repositories.

すべてのソースコードを1つの作業ディレクトリで管理することが推奨されているらしい。

Most Go programmers keep all their Go source code and dependencies in a single workspace.

会社なんかで、閉じたソース管理システム使って複数人で作業ディレクトリを共有して開発、という場合だとどうなるんだろうか。。。

22
19
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
22
19