【Go】基本的なgoコマンド

スポンサーリンク

はじめに

超基本的なGoコマンドについてまとめてみます。

go run

go runは、Goのプログラムをコンパイルかつ実行するコマンドです。直接実行しているのかのように実行できます。

go run [build flags] [-exec xprog] package [arguments...]
go command - cmd/go - Go Packages
GoisatoolformanagingGosourcecode.

試してみる

下記のような簡単なプログラムを用意します。

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]
go command - cmd/go - Go Packages
GoisatoolformanagingGosourcecode.

試してみる

下記のような簡単なプログラムを用意します。

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 command - cmd/go - Go Packages
GoisatoolformanagingGosourcecode.

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]
go command - cmd/go - Go Packages
GoisatoolformanagingGosourcecode.

試してみる

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.
  ...
GitHub - rakyll/hey: HTTP load generator, ApacheBench (ab) replacement
HTTPloadgenerator,ApacheBench(ab)replacement.Contributetorakyll/heydevelopmentbycreatinganaccountonGitHub.

go fmt & goimports

go fmtでは、標準の形式にフォーマットしてくれます。

go fmt [-n] [-x] [packages]
go command - cmd/go - Go Packages
GoisatoolformanagingGosourcecode.

また、goimportsというimport文もフォーマットしてくれるツールも用意されており、下記のコマンドでインストールできます。

go install golang.org/x/tools/cmd/goimports@latest
tools/cmd/goimports at master · golang/tools
GoTools.Contributetogolang/toolsdevelopmentbycreatinganaccountonGitHub.

試してみる

下記のような不要なライブラリやスペースによる字下げがあるプログラムを用意します。

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
go command - cmd/go - Go Packages
GoisatoolformanagingGosourcecode.

また、似たようなツールで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

参考

タイトルとURLをコピーしました