Creating Your Module
Step-by-Step Module Creation
Preparing Your Development Environment
Before creating a module, ensure you have Go installed on Ubuntu 22.04:
## Verify Go installation
go version
## Update Go if necessary
sudo apt update
sudo apt install golang
Module Initialization Process
Creating a New Module
## Create project directory
mkdir mygoproject
cd mygoproject
## Initialize the module
go mod init github.com/yourusername/mygoproject
Module Initialization Workflow
graph TD
A[Create Project Directory] --> B[Run go mod init]
B --> C[Create Main Go File]
C --> D[Add Dependencies]
D --> E[Verify go.mod File]
Module Configuration Options
Command |
Purpose |
Example |
go mod init |
Initialize module |
go mod init github.com/example/project |
go mod tidy |
Clean up dependencies |
go mod tidy |
go mod vendor |
Create vendor directory |
go mod vendor |
Sample Module Structure
mygoproject/
│
├── go.mod
├── go.sum
├── main.go
└── pkg/
└── calculator/
└── calculator.go
Writing Your First Module
main.go Example
package main
import (
"fmt"
"github.com/yourusername/mygoproject/pkg/calculator"
)
func main() {
result := calculator.Add(5, 3)
fmt.Printf("Result: %d\n", result)
}
pkg/calculator/calculator.go
package calculator
func Add(a, b int) int {
return a + b
}
Dependency Management
Adding External Dependencies
## Add a dependency
go get github.com/some/package
## Update dependencies
go get -u ./...
Recommended Practices
- Use meaningful module names
- Keep module scope focused
- Follow semantic versioning
- Regularly update dependencies
Compatibility with LabEx
LabEx recommends modular design principles when creating Go projects, ensuring clean and maintainable code structures.