A technical article about Go package management
Purpose: Previously, I wanted to reference another project I wrote within a Go project, but got stuck for hours and even considered giving up.
1 Creating Projects
We create a directory called gogogo, which contains two projects:
Create main.go files separately
utils/main.go
1 | package utils |
demo/main.go
1 | package main |
2 Initialize each project (using go mod init project_name)
1 | cd demo |
1 | cd utils |
At this point, the code structure looks like this, with go.mod auto-generated:
!!!Note: If the project name you use with init contains Go keywords or reserved names, it will fail!!!
3 The Key Step: Modify go.mod
Use the replace directive to specify the directory corresponding to the imported package:
Then run: go mod tidy (This command lets Go handle dependencies; if there are remote dependencies, they will be
downloaded automatically.)
As a result, you might notice that go.mod has changed slightly!
4 Running the Go Code
Option 1: Run directly using go run
1 | go run main.go |
Option 2: Build an executable and run it
1 | go build |