モジュールを初期化する
プロジェクトのフォルダーでモジュールを初期化すると、依存関係をgo.modに記録できます。
基本コマンドCOMMAND
go mod init example.com/hello整形・テスト・ビルド
プロジェクトで実行COMMAND
go fmt ./...
go test ./...
go build依存関係外部パッケージを追加した後は
go mod tidyでgo.modとgo.sumを整えます。multiply.goGO
package main
func multiply(left, right int) int {
return left * right
}multiply_test.goGO
package main
import "testing"
func TestMultiply(t *testing.T) {
if got := multiply(6, 7); got != 42 {
t.Fatalf("got %d, want 42", got)
}
}実行結果OUTPUT
ok example.com/hello 0.002s再現できる環境を作る
テストと依存関係をリポジトリに含めると、別の環境でも同じ確認を実行できます。次はGo練習問題へ進みましょう。
