はじめに
超基本的なGoコマンドについてまとめてみます。
go run
go run
は、Goのプログラムをコンパイルかつ実行するコマンドです。直接実行しているのかのように実行できます。
go run [build flags] [-exec xprog] package [arguments...]
試してみる
下記のような簡単なプログラムを用意します。
package main
import "fmt"
func main() {
fmt.Println("Hello World!!")
}
go run
で実行してみても、実行形式のファイルがないまま実行できています。
❯ go run main.go
Hello World!!
❯ ls
main.go
go build
go build
はGoプログラムをコンパイルして、実行形式のファイルを作成してくれます。
go build [-o output] [build flags] [packages]
試してみる
下記のような簡単なプログラムを用意します。
package main
import "fmt"
func main() {
fmt.Println("Hello World!!")
}
go build
でコンパイルすると、実行形式のファイルが作成されているのが確認できます。
❯ go build main.go
❯ ls
main main.go
-o
で実行形式の名前を指定できます。
❯ go build -o hello-world main.go
❯ ls
hello-world main.go
go mod
go mod
は、モジュールの管理に関するコマンドです。
go mod <command> [arguments]
go mod init
でモジュールの初期化ができ、go mod tidy
で必要なライブラリのダウンロードや不要なファイルの削除をしてくれます。
go mod init [module-path]
go mod tidy [-e] [-v] [-x] [-go=version] [-compat=version]
試してみる
下記のような簡単なプログラムを用意します。
package main
import "fmt"
func main() {
fmt.Println("Hello World!!")
}
まずはgo mod init
で初期化します。
go mod init hello-world
すると、go.mod
というファイルが作成されます。
module hello-world
go 1.20
今回は何も起きませんが、go mod tidy
で必要なモジュールと不要なモジュールの削除をしておきます。また、go.mod
ファイルがあるとgo build
のみでコンパイルできます。
❯ go mod tidy
❯ go build
❯ ls
go.mod hello-world main.go
go install
go install
は、公開されているプログラムのダウンロードとコンパイルを行うことができます。
go install [build flags] [packages]
試してみる
heyというロードテストが行えるツールをインストールしてみます。インストールできると、実行形式のファイルができるので下記のようにhey
を実行できるようになります。
❯ go install github.com/rakyll/hey@latest
❯ hey -h
flag needs an argument: -h
Usage: hey [options...] <url>
Options:
-n Number of requests to run. Default is 200.
-c Number of workers to run concurrently. Total number of requests cannot
be smaller than the concurrency level. Default is 50.
...
go fmt & goimports
go fmt
では、標準の形式にフォーマットしてくれます。
go fmt [-n] [-x] [packages]
また、goimports
というimport文もフォーマットしてくれるツールも用意されており、下記のコマンドでインストールできます。
go install golang.org/x/tools/cmd/goimports@latest
試してみる
下記のような不要なライブラリやスペースによる字下げがあるプログラムを用意します。
package main
import "fmt"
import "context" // 不要なライブラリ
func main() {
fmt.Println("Hello World!!") // スペースによる字下げ
}
goimports
を実行してみます。
-l
: フォーマットが正しくないファイルを表示-w
: ファイルを直接書き換える
❯ goimports -l -w .
main.go
フォーマットされているのが確認できます。
package main
import "fmt"
func main() {
fmt.Println("Hello World!!")
}
go vet & staticcheck
get vet
は、Goのプログラムを静的解析してくれるコマンドです。
go vet [-C dir] [-n] [-x] [-vettool prog] [build flags] [vet flags] [packages]
go tool vet help
でチェックしてくれる項目が確認できます。
❯ go tool vet help
vet is a tool for static analysis of Go programs.
vet examines Go source code and reports suspicious constructs,
such as Printf calls whose arguments do not align with the format
string. It uses heuristics that do not guarantee all reports are
genuine problems, but it can find errors not caught by the compilers.
Registered analyzers:
asmdecl report mismatches between assembly files and Go declarations
assign check for useless assignments
atomic check for common mistakes using the sync/atomic package
bools check for common mistakes involving boolean operators
buildtag check that +build tags are well-formed and correctly located
cgocall detect some violations of the cgo pointer passing rules
composites check for unkeyed composite literals
copylocks check for locks erroneously passed by value
errorsas report passing non-pointer or non-error values to errors.As
framepointer report assembly that clobbers the frame pointer before saving it
httpresponse check for mistakes using HTTP responses
ifaceassert detect impossible interface-to-interface type assertions
loopclosure check references to loop variables from within nested functions
lostcancel check cancel func returned by context.WithCancel is called
nilfunc check for useless comparisons between functions and nil
printf check consistency of Printf format strings and arguments
shift check for shifts that equal or exceed the width of the integer
sigchanyzer check for unbuffered channel of os.Signal
stdmethods check signature of methods of well-known interfaces
stringintconv check for string(int) conversions
structtag check that struct field tags conform to reflect.StructTag.Get
testinggoroutine report calls to (*testing.T).Fatal from goroutines started by a test.
tests check for common mistaken usages of tests and examples
timeformat check for calls of (time.Time).Format or time.Parse with 2006-02-01
unmarshal report passing non-pointer or non-interface values to unmarshal
unreachable check for unreachable code
unsafeptr check for invalid conversions of uintptr to unsafe.Pointer
unusedresult check for unused results of calls to some functions
また、似たようなツールでstatickcheck
というツールがあります。
下記でインストールできます。
go install honnef.co/go/tools/cmd/staticcheck@latest
試してみる
下記のような未使用の変数が含まれているプログラムを用意します。
package main
import "fmt"
func main() {
var x int = 10 // 未使用の変数
fmt.Println("Hello World!!")
}
go vet
を実行すると、未使用の変数の警告が出てきます。
❯ go vet
# hello-world
vet: ./main.go:6:6: x declared and not used