0
0
GoHow-ToBeginner · 3 min read

How to Create a Go Module: Step-by-Step Guide

To create a Go module, run go mod init <module-name> in your project folder. This command creates a go.mod file that manages your module's dependencies and versioning.
📐

Syntax

The basic syntax to create a Go module is:

go mod init <module-name>

Here:

  • go mod init is the command to initialize a new module.
  • <module-name> is the name of your module, usually a repository path like github.com/username/project.
  • This command creates a go.mod file in your project directory.
bash
go mod init github.com/username/project
💻

Example

This example shows how to create a Go module and write a simple program that uses it.

go
package main

import "fmt"

func main() {
    fmt.Println("Hello, Go module!")
}
Output
Hello, Go module!
⚠️

Common Pitfalls

Common mistakes when creating Go modules include:

  • Running go mod init outside your project folder.
  • Using an invalid module name that is not a valid import path.
  • Not committing the go.mod file to version control.
  • Forgetting to run go mod tidy to clean unused dependencies.
bash
Wrong:
$ go mod init myproject

Right:
$ go mod init github.com/username/myproject
📊

Quick Reference

  • Initialize module: go mod init <module-name>
  • Download dependencies: go mod tidy
  • Check module info: go list -m all
  • Build project: go build

Key Takeaways

Run go mod init <module-name> inside your project folder to create a Go module.
The go.mod file tracks your module's dependencies and versions automatically.
Use valid module names that look like repository paths (e.g., github.com/username/project).
Run go mod tidy to add missing and remove unused dependencies.
Always commit your go.mod and go.sum files to version control.