0
0
Goprogramming~5 mins

Go modules overview

Choose your learning style9 modes available
Introduction

Go modules help you manage your project's code and its external libraries easily. They make sure your project uses the right versions of code it needs.

When you start a new Go project and want to keep track of its dependencies.
When you want to share your Go code with others and make it easy to use.
When you need to update or fix external libraries your project uses.
When you want to build your project reliably on different computers.
When you want to avoid conflicts between different versions of libraries.
Syntax
Go
go mod init <module-name>
go mod tidy
go mod download
go mod verify

go mod init creates a new module with the given name.

go mod tidy cleans up and adds missing dependencies.

Examples
This starts a new module named github.com/yourname/projectname.
Go
go mod init github.com/yourname/projectname
This command adds missing dependencies and removes unused ones.
Go
go mod tidy
This downloads all the dependencies needed for your project.
Go
go mod download
This checks that dependencies have not been changed or corrupted.
Go
go mod verify
Sample Program

This simple program uses the external package rsc.io/quote to print a Go quote. You need to use Go modules to manage this external package.

Go
package main

import (
	"fmt"
	"rsc.io/quote"
)

func main() {
	fmt.Println(quote.Go())
}
OutputSuccess
Important Notes

Always run go mod tidy after adding or removing imports to keep your module file clean.

Your module name usually matches the repository URL if you plan to share your code.

Go modules work outside of GOPATH, so you can keep your projects anywhere on your computer.

Summary

Go modules help manage project dependencies and versions easily.

Use go mod init to start a module and go mod tidy to keep dependencies clean.

Modules make your Go projects more reliable and easier to share.