Welcome to the exciting world of Go programming! In this lesson, we'll dive into Go Modules - a powerful dependency management system for Go projects.
Go Modules help manage dependencies (libraries) in your Go projects, making it easier to reuse code and manage multiple projects with different dependencies.
go env -w GO111MODULE=onmkdir my-go-app
cd my-go-app
go mod init my-go-appNow, you have a new Go project with Go Modules enabled!
To add a dependency, create a go.mod file with the required dependency information. For example, to add the encoding/json package:
go get encoding/jsonNow, let's create a simple program using the encoding/json package:
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
p := Person{"John Doe", 30}
j, _ := json.Marshal(p)
fmt.Println(string(j))
}Run the program:
go run main.goGo Modules keep track of all your project's dependencies and their versions. You can view the current dependencies in your go.mod file.
To update a dependency, run:
go get -u <dependency>Go Modules generate a go.sum file, which stores hashes of your project's dependencies. This ensures that you download the exact same code when you update your dependencies, improving the security of your project.
What does Go Modules help manage in Go projects?
That's it for this introduction to Go Modules! In the next lesson, we'll dive deeper into managing dependencies and creating custom Go modules. Stay tuned! 🎯