FreeStyleWiki

Go言語でパッケージ作成

このエントリーをはてなブックマークに追加

[Go]

Go言語でパッケージ作成

Creating Your Own Package in Go を翻訳。

  • すでに GOの環境構築? でGOPATHなどは設定済みとする

解説の翻訳

  Step1

 Create a directory inside your workspace to keep source code of a package, for me it’s numberutil under $GOPATH/github.com/arpitaggarwal:

パッケージのソースコードを保持するワークスペースの中にディレクトリを作成する、自分の場合:$GOPATH/github.com/arpitaggarwal 以下 '''

$ mkdir -p $GOPATH/github.com/arpitaggarwal/numberutil

  Step2

 Move to directory we created in previous step and create a file named decimalTobinary.go inside it, as follows:

先程の工程で作成したディレクトリまで移動し、decimalTobinary.goという名前のファイルをその中に作る、以下のように:

$ cd $GOPATH/github.com/arpitaggarwal/numberutil
$ touch decimalTobinary.go
 Copy following Go code:

以下のGoのコードをコピーする

package numberutil
 
import "strconv"
 
//Convert Decimal to Binary
func DecimalToBinary(decimal int64) string {
    binary := strconv.FormatInt(decimal, 2)
    return binary
}
 Above code contains a single go function which takes Decimal number as input and convert it to Binary using strconv.FormatInt function.

上のコードにはstrconv.FormatIntを使用して10進数の数値をバイナリに変換するgoの関数が含まれる。

  Step3

 Build numberutil package using go tool, as follows:

numberutilパッケージをgoのツールを使用してビルドする、以下のように:

$ cd $GOPATH
$ go build github.com/arpitaggarwal/numberutil

  Step4

 Next we will create '''number-util.go''' with a '''main()''' method to use '''DecimalToBinary''' function from '''numberutil''' package we created, as follows:

次に、numberutilパッケージからDecimalToBinary関数を使用するためのmain関数を持ったnumber-util.goを作成する、以下のように:

$ cd $GOPATH/github.com/arpitaggarwal/
$ touch number-util.go
 Copy following Go code:

以下のGoのコードをコピーする:

package main
 
import (
    "fmt"
    "github.com/arpitaggarwal/numberutil"
)
 
func main() {
    i23 := int64(23)
    fmt.Printf("Decimal to Binary for 23 is %s \n", numberutil.DecimalToBinary(i23))
}

  Step5

 Install number-util.go using go tool:

goのツールを使用してnumber-util.goをインストールする:

$ go install $GOPATH/github.com/arpitaggarwal/number-util.go
 Above command compile number-util.go and generate executable binary file of it in $GOROOT/bin or $GOBIN directory.

上記のコマンドはnumber-util.goをコンパイルし、実行可能バイナリファイルを$GOROOT/bin$GOBINのディレクトリに生成する。

  Step6

 Run number-util.go moving to golang directory:

golangディレクトリに移動してnumber-util.goを実行する:

$ cd golang
$ ./go/bin/number-util

  Step7

 Now we will generate documentation of numberutil package we created which is as simple as running godoc tool with -http flag for the port number from the terminal, as follows:

これでnumberutilパッケージのドキュメントを生成できる、これは以下のように端末からポート番号を-httpフラグとともに指定してgodocを単純に起動すれば良い:

godoc -http=:9999
 Now, opening http://localhost:9999/pkg/github.com/arpitaggarwal/numberutil/ in browser will show us the documentation of numberutil package we have created.

これで http://localhost:9999/pkg/github.com/arpitaggarwal/numberutil/ をブラウザで開けば、作成したnumberutilパッケージについてのドキュメントが見られる。