BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Modules

Go 1.23

Go Modules are the official dependency management system for Go. This example shows how to import external packages and explains the workflow for initializing modules, adding dependencies, and maintaining the `go.mod` and `go.sum` files.

Code

package main

import (
    "fmt"
    
    // Importing an external package
    // Run 'go get rsc.io/quote' to add this dependency
    "rsc.io/quote"
)

func main() {
    fmt.Println("Go Modules Demo")
    
    // Use a function from the imported package
    fmt.Println(quote.Go())
}

/*
SETUP INSTRUCTIONS:

1. Initialize a new module:
   $ go mod init example/hello

2. Add the dependency (and download it):
   $ go get rsc.io/quote
   
   This updates go.mod and creates go.sum.

3. Run the program:
   $ go run .
*/

Explanation

Go Modules provide a structured way to manage dependencies in Go projects. A module is a collection of related Go packages that are versioned together as a single unit. The system is defined by the go.mod file, which sits at the root of your project and declares the module path (the project's unique identity) and its dependency requirements.

When you import a package that isn't in the standard library, Go looks at your go.mod file to resolve the version. The go get command is used to add, upgrade, or remove dependencies. Additionally, a go.sum file is automatically generated to maintain cryptographic checksums of the specific module versions you use, ensuring that your builds are reproducible and secure against tampering.

Key commands for module management:

  • go mod init [module-path]: Initialize a new module in the current directory.
  • go get [package]: Add a dependency or upgrade it.
  • go mod tidy: Remove unused dependencies and add missing ones.
  • go mod verify: Check that dependencies match the expected checksums.

Code Breakdown

8
Importing "rsc.io/quote". This is a popular example package. Since it's not in the standard library, Go needs to know where to find it. This is where the go.mod file comes in.
15
Calling quote.Go(). This function returns a string with a Go proverb. The compiler links this call to the specific version of the package defined in your go.mod file.
22-23
"go mod init" creates the go.mod file. You typically run this once when starting a project. The module path (example/hello) acts as a prefix for package imports within the project.
25-26
"go get" downloads the source code for the dependency and updates your go.mod file to require it. It also updates go.sum with the checksums.