Go modules and package structure¶
In Go, the code organization relies on two primary hierarchical units: Packages and Modules^[400-devops-09-scripting-language-golang-introduction-readme.md].
Packages¶
A Package consists of source files located within the same directory that are compiled together^[400-devops-09-scripting-language-golang-introduction-readme.md]. All source files within a single package share visibility, meaning they can access each other's unexported identifiers^[400-devops-09-scripting-language-golang-introduction-readme.md].
Every Go source file must declare a package name at the top (e.g., package main or package customers).
Modules¶
A Module is a collection of related Go packages that are released, versioned, and distributed together^[400-devops-09-scripting-language-golang-introduction-readme.md]. While a repository can contain multiple modules, it is standard practice to maintain a single module at the root of the repository^[400-devops-09-scripting-language-golang-introduction-readme.md].
Modules are defined by a go.mod file, which serves two main purposes^[400-devops-09-scripting-language-golang-introduction-readme.md]:
- Declaration: It declares the module path (e.g.,
github.com/user/project). - Dependency Management: It specifies the import paths required to download dependencies.
The module path allows other programs to import and consume the module's code^[400-devops-09-scripting-language-golang-introduction-readme.md].
Initialization¶
To initialize a new module, the go mod init command is used within the application's directory^[400-devops-09-scripting-language-golang-introduction-readme.md]. This command creates the go.mod file and sets the module path, which effectively establishes the root of the module for import purposes^[400-devops-09-scripting-language-golang-introduction-readme.md].
Related Concepts¶
- [[Go Standard Library]]
- [[Dependency Management]]
Sources¶
- 400-devops-09-scripting-language-golang-introduction-readme.md