up:: [[Golang MOC]] tags:: #on/computing/programming/languages/golang # Modules and Dependency Management in Golang - Modules are defined by a `go.mod` file (similar to `package.json`?) - Use `go mod init <module_name>` to create a `go.mod` file - A `main` function executes by default when you run the `main` package - Published modules can be found at https://pkg.go.dev - In a module, you collect one or more related packages for a discrete and useful set of functions[^1] - Go code is grouped into packages, and packages are grouped into modules[^1] ## Packages - Packages are used to organize Go source code for better reusability and readability. Packages are a collection of Go sources files that reside in the same directory.[^2] - All Go files that belong to a package should be placed in separate folders of their own. It is a convention in Go to name this folder with the same name as the package.[^2] ### The `init` Function Each package in Go can contain an `init` function. This function must **not** have a return type and it must **not** have any parameters. It cannot be called explicitly in your source code.[^2] It will be called *once* automatically when the package is initialized and *only* during that time. Below is an example of an `init` function. ```go package example import "fmt" func init() { fmt.Println("This runs at package initialization.") } ``` Some uses of the `init` function include: - Performing initialization tasks such as connecting to a database or registering with service registries - Verifying the correctness of a program before execution starts The order of initialization of a package is as follows:[^2] 1. Package-level variables are initialized. 2. The `init` function is called. If a package imports other packages, the imported packages are initialized first. A package will be initialized only once even if it is imported from multiple packages.[^2] > [!tip] > A package can have multiple `init` functions. They are called in the order that they are presented to the compiler. ## Modules - A Go module is just a collection of Go packages.[^2] - The import path for custom packages is derived from the name of their modules[^2] - Third-party packages are managed by the `go.mod` file[^2] ### Initialization To initialize a new Go module: ```bash go mod init <module_name> ``` Here, `module_name` will act as the base path to import any package created inside the module. # Footnotes [^1]: “Tutorial: Create a Go Module - The Go Programming Language.” Accessed August 2, 2024. [https://go.dev/doc/tutorial/create-module](https://go.dev/doc/tutorial/create-module). [^2]: golangbot. “Go Packages,” April 1, 2024. [https://golangbot.com/go-packages/](https://golangbot.com/go-packages/).