Creating and Using Modules
Setting Up a New Module Project
Step 1: Create Project Directory
mkdir hello-module
cd hello-module
Step 2: Initialize Module
go mod init github.com/yourusername/hello-module
Module Project Structure
graph TD
A[Module Root] --> B[go.mod]
A --> C[main.go]
A --> D[pkg/]
D --> E[utility.go]
Writing Module Code
Creating Main Package
// main.go
package main
import (
"fmt"
"github.com/yourusername/hello-module/pkg/greeting"
)
func main() {
message := greeting.Hello("LabEx")
fmt.Println(message)
}
Creating Utility Package
// pkg/greeting/greeting.go
package greeting
func Hello(name string) string {
return "Hello, " + name + "!"
}
Module Dependency Management
Adding External Dependencies
go get github.com/some/external/package
Dependency Management Commands
Command |
Purpose |
go mod tidy |
Clean up dependencies |
go mod vendor |
Create vendor directory |
go list -m all |
List all dependencies |
Building and Running
## Download dependencies
go mod download
## Build the project
go build
## Run the application
go run main.go
Version Control Integration
## Initialize git repository
git init
git add .
git commit -m "Initial module setup"
Advanced Module Techniques
Local Module Development
## Replace module with local path
go mod edit -replace github.com/example/module=../local/path
Versioning Modules
## Tag a version
git tag v1.0.0
git push origin v1.0.0
Best Practices
- Use meaningful module paths
- Keep
go.mod
and go.sum
in version control
- Use semantic versioning
- Minimize external dependencies
Working with LabEx
LabEx provides an integrated environment for module development, supporting:
- Automatic dependency management
- Easy project initialization
- Consistent development workflows