Goはパッケージ(ディレクトリ内のソースファイルの集合)とモジュール(バージョン管理された依存関係を持つパッケージの集合)でコードを整理します。これらは一緒にプロジェクトを構造化し、依存関係を管理します。
パッケージ — 関連コードのディレクトリ
main
mathutil
{ a + b }
{}
1つのディレクトリ内のすべてのファイルは1つのパッケージに属します。大文字化は可視性を制御します:大文字で始まる名前はエクスポート(パッケージ間でパブリック)、小文字はパッケージ内でプライベートです。
import (
"fmt" // standard library
"strings"
"github.com/user/repo/mathutil" // a third-party or local module package
)
fmt.Println(strings.ToUpper("hi"))
mathutil.Add(2, 3) // use Exported names via package.Name
go mod init github.com/user/myapp # create a module → makes go.mod
go get github.com/gin-gonic/gin # add a dependency (records it in go.mod)
go mod tidy # add missing & remove unused dependencies
go build # build using the module's dependencies
go.mod — declares the module path, Go version, and direct dependencies (+ versions)
go.sum — cryptographic checksums of dependencies (integrity/security)
モジュール(Go 1.11で導入)は依存関係管理の単位です — go.modは正確な依存関係バージョンをリストアップし、ビルドを再現可能にします。go.sumは依存関係の整合性を検証します。
package main
func init() { // runs automatically when the package loads (before main)
// setup
}
func main() { // entry point of an executable (package main only)
}
myapp/
go.mod
main.go package main
internal/ packages here are PRIVATE to this module (can't be imported externally)
pkg/ or other dirs/ reusable packages
internal/ディレクトリは特別です — そのパッケージは同じモジュール内からのみインポート可能で、モジュールレベルでのカプセル化を強制します。
パッケージとモジュールは、Goプロジェクトがどのように構造化されるか、依存関係がどのように管理されるかの基本です — 実際のプロジェクトに不可欠です。
パッケージ(ファイルのディレクトリ、大文字化ベースのエクスポート/非エクスポート可視性、特別なmainパッケージ)を理解することは、コードを整理し、そのパブリックAPIを制御するための基礎です。
モジュール(go mod、go.mod/go.sum)は再現可能でバージョン管理され、整合性がチェックされた依存関係管理を提供します — 古いGOPATHアプローチに代わる現代的な標準です。
importシステム、モジュール内プライベートコード用のinternal/慣例、ツール(go mod init/tidy、go get)を知ることは、Goプロジェクトの構築、共有、保守に必要であり、Goエコシステムへの実践的な精通を反映しています。